Reflection in Java is a effective function that lets in programs to look at and manage
classes, methods, fields,
and constructors at runtime — although their names are not known until execution.
1. What Can You Do With Reflection?
Using reflection, you can:
Get information about a class (name, methods, fields, constructors, etc.)
Instantiate objects dynamically
Invoke methods dynamically
Access or modify fields, even private ones
2. How to Use Reflection
Reflection is available in the java.lang.reflect package. You typically start by getting the
Class object of the target class.
public class Demo {
public int num;
private String text;
public void sayHello() {
System.out.println("Hello");
}
}
public class ReflectionInfo {
public static void main(String[] args) {
Class<?> clazz = Demo.class;
System.out.println("Class Name: " + clazz.getName());
System.out.println("\nFields:");
for (Field field : clazz.getDeclaredFields()) {
System.out.println(field.getName());
}
System.out.println("\nMethods:");
for (Method method : clazz.getDeclaredMethods()) {
System.out.println(method.getName());
}
}
}
b. Accessing and Modifying Fields
import java.lang.reflect.Field;
public class ReflectionFieldAccess {
public static void main(String[] args) throws Exception {
Demo demo = new Demo();
Class<?> clazz = demo.getClass();
Field field = clazz.getDeclaredField("text");
field.setAccessible(true); // Allow access to private field
field.set(demo, "Reflection Rocks!");
System.out.println("Value of text: " + field.get(demo));
}
}
c. Invoking Methods Dynamically
import java.lang.reflect.Method;
public class ReflectionMethodInvoke {
public static void main(String[] args) throws Exception {
Demo demo = new Demo();
Class<?> clazz = demo.getClass();
Method method = clazz.getDeclaredMethod("sayHello");
method.invoke(demo); // calls demo.sayHello()
}
}
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
Reflection in Java is a effective function that lets in programs to look at and manage classes, methods, fields, and constructors at runtime — although their names are not known until execution.
1. What Can You Do With Reflection?
Using reflection, you can:
2. How to Use Reflection
Reflection is available in the
java.lang.reflectpackage. You typically start by getting theClassobject of the target class.Or, if you have the object:
3. Examples of Using Reflection
a. Get Class Information
b. Accessing and Modifying Fields
c. Invoking Methods Dynamically
d. Creating Object Using Constructor
4. Important Notes