⬅ Previous Topic
Java EnumsNext Topic ⮕
Exceptions in Java⬅ Previous Topic
Java EnumsNext Topic ⮕
Exceptions in JavaReflection 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.
The Java Reflection API is primarily built around classes from the java.lang.reflect
package:
Class
- Represents classes and interfacesMethod
- Represents class methodsField
- Represents class variablesConstructor
- Represents class constructorsTo 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
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
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
Method method = clazz.getMethod("show");
method.invoke(obj);
Hello from MyClass!
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();
Constructor<?> constructor = clazz.getDeclaredConstructor();
System.out.println("Constructor: " + constructor.getName());
Constructor: MyClass
Reflection plays a crucial role in:
Class<?>
object in Java?Field secretField = clazz.getDeclaredField("secret");
secretField.setAccessible(true);
String secretValue = (String) secretField.get(obj);
System.out.println("Secret: " + secretValue);
⬅ Previous Topic
Java EnumsNext Topic ⮕
Exceptions in JavaYou 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.