Yandex

Java Advanced ConceptsJava Advanced Concepts3

Java ReferenceJava Reference1

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?

Key Classes in the Reflection API

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

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

Use Cases in Real-World Development

Reflection plays a crucial role in:

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?



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M