Java Reflection
What is Reflection?
Reflection is Java's ability to look into and change classes, methods, fields, and constructors at runtime. It allows you to examine or modify the behavior of applications during execution.
Capabilities:
Use Cases:
Understanding the Class Object
The java.lang.Class class is the entry point for reflection. Every loaded class has exactly one Class object that contains its metadata.
What Class Object Contains:
Important: The JVM creates one Class object per loaded class, stored in the Method Area.
Obtaining Class Objects
There are three primary ways to obtain a Class object:
Method 1: Using .class Literal (Compile-time)
// Most efficient - no object instance needed
Class<?> userClass = User.class;
When to use: When you know the class name at compile time.
Method 2: Using getClass() Method (Runtime)
User user = new User("Deepak", "deepak@email.com");
Class<?> userClass = user.getClass();
When to use: When you have an object instance.
Method 3: Using Class.forName() (Dynamic Loading)
try {
// Loads the class if not already loaded
Class<?> userClass = Class.forName("com.vodafone.model.User");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
When to use: When class name is determined at runtime (e.g., from configuration files, database).
Complete Example:
Recommended by LinkedIn
Reflection on Constructors
Constructor<?>[] constructors = MyClass.class.getDeclaredConstructors();
Reflection on Fields
Field field = MyClass.class.getDeclaredField("name");
field.setAccessible(true);
Reflection on Methods
Method method = MyClass.class.getDeclaredMethod("doWork");
method.setAccessible(true);
How to call a private constructor using Reflection?
Reflection allows bypassing Java access control using: constructor.setAccessible(true);
How to create an object using a private constructor?
class MyClass {
private MyClass() {
System.out.println("Private constructor called");
}
}
import java.lang.reflect.Constructor;
public class TestReflection {
public static void main(String[] args) throws Exception {
Class<MyClass> clazz = MyClass.class;
Constructor<MyClass> constructor =
clazz.getDeclaredConstructor();
constructor.setAccessible(true); // bypass private
MyClass obj = constructor.newInstance(); // object created
}
}
Important:
Why Reflection Should Be Used Carefully
Reflection gives power, not safety — use it only when really need it.
Keep learning and growing