Reflection in Java

1. What is Reflection in Java?

Reflection is a feature in Java that allows a program to inspect and manipulate classes, methods, fields, and constructors at runtime, even if you don’t know their names at compile time.

It’s like having a “mirror” into the internals of a class.

Key uses:

  • Inspect class information at runtime
  • Access private fields and methods
  • Create objects dynamically
  • Analyze annotations

2. Main Classes in Reflection

Java provides reflection functionality through the java.lang.reflect package and the Class class:

  • Class → Represents a class or interface
  • Method → Represents a method
  • Field → Represents a field
  • Constructor → Represents a constructor
  • Modifier → Helps to check modifiers (public, private, static)

3. Getting a Class Object

You can obtain a Class object in several ways:

// 1. Using .class
Class<MyClass> clazz1 = MyClass.class;

// 2. Using an instance
MyClass obj = new MyClass();
Class<?> clazz2 = obj.getClass();

// 3. Using Class.forName()
Class<?> clazz3 = Class.forName("com.example.MyClass");

4. Inspecting Class Information

You can inspect methods, fields, constructors, and more:

Class<?> clazz = MyClass.class;

// Get class name
System.out.println(clazz.getName());

// Get fields
Field[] fields = clazz.getDeclaredFields();
for(Field f : fields){
    System.out.println(f.getName() + " : " + f.getType());
}

// Get methods
Method[] methods = clazz.getDeclaredMethods();
for(Method m : methods){
    System.out.println(m.getName());
}

// Get constructors
Constructor<?>[] constructors = clazz.getDeclaredConstructors();
for(Constructor<?> c : constructors){
    System.out.println(c.getName());
}

5. Accessing Private Fields and Methods

Reflection can access private members, but you need to call setAccessible(true):

import java.lang.reflect.Field;
import java.lang.reflect.Method;

class Person {
    private String name = "John";
    private void sayHello() {
        System.out.println("Hello, " + name);
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        Person p = new Person();
        Class<?> clazz = p.getClass();

        // Access private field
        Field nameField = clazz.getDeclaredField("name");
        nameField.setAccessible(true);
        nameField.set(p, "Alice"); // Modify value

        // Access private method
        Method sayHello = clazz.getDeclaredMethod("sayHello");
        sayHello.setAccessible(true);
        sayHello.invoke(p); // Prints: Hello, Alice
    }
}

6. Creating Objects Dynamically

Reflection can be used to create objects at runtime without using new:

Constructor<MyClass> constructor = MyClass.class.getConstructor();
MyClass obj = constructor.newInstance();

7. Advantages of Reflection

  • Enables dynamic and flexible code
  • Useful for frameworks (like Spring, Hibernate)
  • Useful for debugging, testing, and serialization

8. Disadvantages of Reflection

  • Slower performance (runtime overhead)
  • Breaks encapsulation (can access private members)
  • Can lead to security issues

Summary

Reflection is a powerful feature for inspecting and manipulating classes at runtime, but it should be used cautiously because of performance and security concerns.

Leave a Reply