Reflection

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • Reflection is an API (java.lang.reflect) that allows Java code to inspect and manipulate classes, methods, and fields at runtime.
  • It allows you to do things the compiler normally prevents, like instantiating private classes or modifying private variables.
  • It is incredibly powerful (used heavily by Spring and Hibernate) but is slow and breaks type safety.

Concept

Normally, you interact with objects statically. The compiler checks that a method exists before letting you call it.

Reflection allows you to write dynamic code that says: “I don’t know what this Object is. At runtime, look at the object. Find a method named ‘initialize’, and if it exists, execute it.”

It is the magic behind Dependency Injection. When you annotate a private field with @Autowired in Spring, Spring uses Reflection to forcefully bypass the private keyword and inject a database connection directly into the variable.

Examples

class SecretVault {
    private String password = "SuperSecretPassword123";
    
    private void selfDestruct() {
        System.out.println("Boom!");
    }
}

public class ReflectionDemo {
    public static void main(String[] args) throws Exception {
        SecretVault vault = new SecretVault();
        
        // 1. Get the Class object
        Class<?> clazz = vault.getClass();
        
        // 2. Read and modify a PRIVATE field
        Field passwordField = clazz.getDeclaredField("password");
        passwordField.setAccessible(true); // <--- The magic bypass!
        
        System.out.println("Stolen Password: " + passwordField.get(vault));
        passwordField.set(vault, "Hacked!");
        
        // 3. Invoke a PRIVATE method
        Method destructMethod = clazz.getDeclaredMethod("selfDestruct");
        destructMethod.setAccessible(true);
        destructMethod.invoke(vault); // Prints "Boom!"
    }
}

Interview Questions

Q: Why shouldn’t you use Reflection in everyday code?
A: 1. Performance: Reflection completely bypasses the JVM’s JIT compiler optimizations. Calling a method via reflection is significantly slower than calling it directly.
2. Security & Stability: It circumvents encapsulation. If a library author changes a private field name from password to pinCode in an update, your reflection code will crash at runtime with a NoSuchFieldException, whereas normal code would fail safely at compile-time.
3. Complexity: It makes code very hard to read and debug.

Q: What is the Class object?
A: In Java, every time a .class file is loaded into the JVM, the JVM creates a special metadata object of type java.lang.Class. This object holds the blueprint of the class (its name, constructors, methods, and annotations). You get it using MyClass.class or myObject.getClass(). This metadata object is the entry point for all Reflection API calls.