What is meta-programming and reflection in OOP?
Why Interviewers Ask This
Interviewers ask this to evaluate whether you have the depth of knowledge needed to mentor others and lead technical decisions. The expected answer goes beyond definitions into practical implications and real-world consequences.
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.
Common Mistake
Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your OOP Concepts experience.