Reflection in Java

Reflection in Java is a powerful and somewhat magical feature. It lets your code inspect and manipulate itself or other classes at runtime. Think of it as a way to peek behind the curtain of how Java classes, fields, and methods are structured and to even tweak them dynamically—without knowing their names at compile time.

Why Use Reflection?

  • To create instances of classes dynamically (useful in frameworks and tools)
  • To inspect metadata (like class names, fields, annotations)
  • To invoke methods or access fields that might otherwise be private
  • To write generic code that can operate on any class

Key Classes in the Reflection API

The Java Reflection API is primarily built around classes from the java.lang.reflect package:

  • Class - Represents classes and interfaces
  • Method - Represents class methods
  • Field - Represents class variables
  • Constructor - Represents class constructors

Getting the Class Object

To begin reflection, we first need a Class object. Here's how:

Class<?> clazz1 = MyClass.class;              // Using .class
Class<?> clazz2 = obj.getClass();             // From an instance
Class<?> clazz3 = Class.forName("MyClass");   // By name

Let’s see a complete example.

class MyClass {
    public int x = 42;
    private String secret = "Hidden Message";

    public void show() {
        System.out.println("Hello from MyClass!");
    }
}
public class ReflectionDemo {
    public static void main(String[] args) throws Exception {
        Class<?> clazz = Class.forName("MyClass");

        Object obj = clazz.getDeclaredConstructor().newInstance();
        System.out.println("Class name: " + clazz.getName());

        // Access public field
        java.lang.reflect.Field field = clazz.getField("x");
        System.out.println("Value of x: " + field.getInt(obj));
    }
}
Class name: MyClass
Value of x: 42

Accessing Private Fields

Reflection even allows access to private fields—something you can’t do through regular code.

Field secretField = clazz.getDeclaredField("secret");
secretField.setAccessible(true);
String secretValue = (String) secretField.get(obj);
System.out.println("Private field value: " + secretValue);
Private field value: Hidden Message

Listing All Fields and Methods

for (Field f : clazz.getDeclaredFields()) {
    System.out.println("Field: " + f.getName());
}

for (Method m : clazz.getDeclaredMethods()) {
    System.out.println("Method: " + m.getName());
}
Field: x
Field: secret
Method: show

Invoking Methods with Reflection

Method method = clazz.getMethod("show");
method.invoke(obj);
Hello from MyClass!

Creating Instances Dynamically

This technique is heavily used in frameworks like Spring or Hibernate where classes are created on-the-fly.

Class<?> dynamicClass = Class.forName("MyClass");
Object instance = dynamicClass.getDeclaredConstructor().newInstance();

Accessing Constructors

Constructor<?> constructor = clazz.getDeclaredConstructor();
System.out.println("Constructor: " + constructor.getName());
Constructor: MyClass

Common Pitfalls and Considerations

  • Performance Overhead: Reflection is slower than direct access
  • Security Restrictions: Accessing private members might throw exceptions if security manager is active
  • Loss of Compile-time Safety: Errors show up only at runtime

Use Cases in Real-World Development

Reflection plays a crucial role in:

  • Frameworks like Spring and Hibernate
  • Dependency Injection
  • Testing Frameworks like JUnit
  • Object Mappers like Jackson or GSON

QUIZ

Question 1:Which class from the Reflection API is used to represent the methods of a Java class?

Question 2:Using reflection, you can access private fields of a class at runtime.

Question 3:Which of the following are valid ways to obtain a Class<?> object in Java?

Question 4:What is the output of the following code?
Field secretField = clazz.getDeclaredField("secret");
secretField.setAccessible(true);
String secretValue = (String) secretField.get(obj);
System.out.println("Secret: " + secretValue);

Question 5:Reflection in Java can be used to create instances of classes dynamically at runtime.

Question 6:Which of the following are valid use cases for Java Reflection?