What is meta-programming and reflection in OOP?

Answer

Reflection allows a program to inspect and modify its own structure and behavior at runtime — examine classes, methods, fields, and call methods dynamically without knowing them at compile time. Java Reflection: // Inspect a class: Class<?> clazz = String.class; System.out.println(clazz.getName()); // "java.lang.String" for (Method method : clazz.getDeclaredMethods()) { System.out.println(method.getName()); } for (Field field : clazz.getDeclaredFields()) { System.out.println(field.getName()); } // Instantiate without knowing the class at compile time: Class<?> cls = Class.forName("com.example.UserService"); Object instance = cls.getDeclaredConstructor().newInstance(); // Call a method dynamically: Method method = cls.getMethod("processUser", String.class); method.invoke(instance, "Alice"); // Accessing private fields (dangerous!): Field field = clazz.getDeclaredField("secretField"); field.setAccessible(true); Object value = field.get(instance);. Annotations (metadata): @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Benchmark {} class MyService { @Benchmark public void performWork() { /* ... */ } } // Read at runtime: for (Method m : service.getClass().getDeclaredMethods()) { if (m.isAnnotationPresent(Benchmark.class)) { long start = System.nanoTime(); m.invoke(service); long duration = System.nanoTime() - start; System.out.println(m.getName() + " took " + duration + "ns"); } }. Uses of reflection: frameworks (Spring IoC, JUnit test discovery), serialization (Jackson), ORM (Hibernate), dependency injection, RPC frameworks. Costs: slow (bypasses JIT optimization), breaks encapsulation (private access), compile-time safety lost. Use with care — prefer compile-time alternatives when possible.