For example, imagine you have a class in Java, and you want to find out what methods it has or what fields it contains at runtime. Reflection enables you to do this. However, using reflection extensively can have performance implications because it involves dynamic discovery and manipulation of the program’s structure, and it might not be as efficient as direct, statically-typed code.
Example
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void sayHello() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
Now, let’s use reflection to inspect and interact with the Person
class at runtime:
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectionExample {
public static void main(String[] args) throws Exception {
// Create an instance of the Person class
Person person = new Person("John Doe", 25);
// Use reflection to get the class of the object
Class<?> personClass = person.getClass();
System.out.println("Class Name: " + personClass.getName());
// Get and print the fields of the class
Field[] fields = personClass.getDeclaredFields();
System.out.println("\nFields:");
for (Field field : fields) {
System.out.println("Field Name: " + field.getName() + ", Type: " + field.getType());
}
// Get and print the methods of the class
Method[] methods = personClass.getDeclaredMethods();
System.out.println("\nMethods:");
for (Method method : methods) {
System.out.println("Method Name: " + method.getName() + ", Return Type: " + method.getReturnType());
}
// Use reflection to set the private field 'name'
Field nameField = personClass.getDeclaredField("name");
nameField.setAccessible(true); // Allow access to private field
nameField.set(person, "Jane Doe"); // Set the value
// Use reflection to invoke the 'sayHello' method
Method sayHelloMethod = personClass.getDeclaredMethod("sayHello");
sayHelloMethod.invoke(person); // Invoke the method
}
}
Explanation:
- We create an instance of the
Person
class. - We use reflection to get the class of the object (
Person
class). - We retrieve and print information about the fields and methods of the class using reflection.
- We use reflection to set the private field
name
to a new value (“Jane Doe”). - We use reflection to invoke the
sayHello
method, which prints a message using the updatedname
.