Java Reflection
Java Reflection is a powerful feature that allows programs to query, access, and modify information about classes, interfaces, fields, and methods at runtime. Reflection provides the ability to dynamically manipulate classes, which is widely used in many frameworks and libraries, such as dependency injection in the Spring framework.
Reflection API
Java's Reflection API provides a series of classes and interfaces for manipulating Class objects. The main classes include:
java.lang.Class: Represents a class object. Provides methods to get the class's fields, methods, constructors, etc.java.lang.reflect.Field: Represents a class's fields (attributes). Provides the ability to access and modify fields.java.lang.reflect.Method: Represents a class's methods. Provides the ability to invoke methods.java.lang.reflect.Constructor: Represents a class's constructors. Provides the ability to create objects.
Workflow
- Get
ClassObject: First, get the target class'sClassobject. - Get member information: Through the
Classobject, you can get information about the class's fields, methods, constructors, etc. - Manipulate members: Through the reflection API, you can read and modify field values, invoke methods, and create objects.
The following are the basic usage methods of Java reflection and their common applications.
1. Getting the Class Object
Every class has an associated Class object in the JVM. You can get the Class object in the following ways:
Through class literals
Class<?> clazz = String.class;
Through an object instance:
String str = "Hello"; Class<?> clazz = str.getClass();
Through the Class.forName() method:
Class<?> clazz = Class.forName("java.lang.String");
2. Creating Objects
You can use reflection to dynamically create objects:
Class<?> clazz = Class.forName("java.lang.String");
Object obj = clazz.getDeclaredConstructor().newInstance();
3. Accessing Fields
You can access and modify class fields through reflection:
Class<?> clazz = Person.class;
Field field = clazz.getDeclaredField("name");
field.setAccessible(true); // 如果字段是私有的,需要设置为可访问
Object value = field.get(personInstance); // 获取字段值
field.set(personInstance, "New Name"); // 设置字段值
4. Invoking Methods
You can invoke class methods through reflection:
Class<?> clazz = Person.class;
Method method = clazz.getMethod("sayHello");
method.invoke(personInstance);
Method methodWithArgs = clazz.getMethod("greet", String.class);
methodWithArgs.invoke(personInstance, "World");
5. Getting Constructors
You can use reflection to get and invoke constructors:
Class<?> clazz = Person.class;
Constructor<?> constructor = clazz.getConstructor(String.class, int.class);
Object obj = constructor.newInstance("John", 30);
6. Getting Interfaces and Parent Classes
You can use reflection to get the interfaces implemented by the class and its parent class:
Class<?> clazz = Person.class;
// 获取所有接口
Class<?>[] interfaces = clazz.getInterfaces();
for (Class<?> i : interfaces) {
System.out.println("Interface: " + i.getName());
}
// 获取父类
Class<?> superClass = clazz.getSuperclass();
System.out.println("Superclass: " + superClass.getName());
The following is a complete example showing how to use reflection to create objects, access fields, and invoke methods:
Example
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectionExample {
public static void main(String[] args) throws Exception {
// Get the Class object
Class<?> clazz = Person.class;
// Create an object
Constructor<?> constructor = clazz.getConstructor(String.class, int.class);
Object person = constructor.newInstance("John", 30);
// Access fields
Field nameField = clazz.getDeclaredField("name");
nameField.setAccessible(true);
System.out.println("Name: " + nameField.get(person));
// Modify fields
nameField.set(person, "Doe");
System.out.println("Updated Name: " + nameField.get(person));
// Invoke methods
Method greetMethod = clazz.getMethod("greet", String.class);
greetMethod.invoke(person, "World");
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void greet(String message) {
System.out.println(name + " says: " + message);
}
}
Compile and execute the above code, the output result is:
Name: John Updated Name: Doe Doe says: World
java.lang.reflect
java.lang.reflectIt is the core package of the Java reflection mechanism, providing classes and interfaces for manipulating classes and their members (fields, methods, constructors, etc.). Through these APIs, developers can dynamically query and modify the structure of classes at runtime.

The following arejava.lang.reflectdetailed introductions to the main classes and interfaces in the package:
1. ClassClass
- Function: Represents a class object, provides methods to get class information, such as fields, methods, constructors, etc.
- Main methods:
getFields(): Get all public fields.getDeclaredFields(): Get all declared fields, including private fields.getMethods(): Get all public methods.getDeclaredMethods(): Get all declared methods, including private methods.getConstructors(): Get all public constructors.getDeclaredConstructors(): Get all declared constructors, including private constructors.getSuperclass(): Get the parent class of the class.getInterfaces(): Get all interfaces implemented by the class.
2. FieldClass
- Function: Represents a class's fields (attributes), provides methods to access and modify field values.
- Main methods:
get(Object obj): Get the field value of the specified object.set(Object obj, Object value): Set the field value of the specified object.getType(): Get the data type of the field.getModifiers(): Get the modifiers of the field (such as public, private).
3. MethodClass
- Function: Represents a class's methods, provides the ability to invoke methods.
- Main methods:
invoke(Object obj, Object... args): Invoke the method of the specified object.getReturnType(): Get the return type of the method.getParameterTypes(): Get the parameter types of the method.getModifiers(): Get the modifiers of the method (such as public, private).
4. ConstructorClass
- Function: Represents a class's constructors, provides the ability to create objects.
- Main methods:
newInstance(Object... initargs): Create a new instance using the specified constructor parameters.getParameterTypes(): Get the parameter types of the constructor.getModifiers(): Get the modifiers of the constructor (such as public, private).
Example Code
The following is an example using thejava.lang.reflectpackage for reflection operations:
Example
import java.lang.reflect.Method;
import java.lang.reflect.Constructor;
public class ReflectionExample {
public static void main(String[] args) throws Exception {
// Get the Class object
Class<?> clazz = Car.class;
// Create a Car object
Constructor<?> constructor = clazz.getConstructor(String.class, int.class);
Object car = constructor.newInstance("Toyota", 2020);
// Access and modify fields
Field modelField = clazz.getDeclaredField("model");
Field yearField = clazz.getDeclaredField("year");
// Set the field as accessible (if the field is private)
modelField.setAccessible(true);
yearField.setAccessible(true);
// Print the original field value
System.out.println("Original Model: " + modelField.get(car));
System.out.println("Original Year: " + yearField.get(car));
// Modify the field value
modelField.set(car, "Honda");
yearField.set(car, 2024);
// Print the modified field value
System.out.println("Updated Model: " + modelField.get(car));
System.out.println("Updated Year: " + yearField.get(car));
// Invoke methods
Method startMethod = clazz.getMethod("start");
startMethod.invoke(car);
}
}
class Car {
private String model;
private int year;
public Car(String model, int year) {
this.model = model;
this.year = year;
}
public void start() {
System.out.println("The " + model + " car of year " + year + " is starting.");
}
}
Compile and execute the above code, the output result is:
Original Model: Toyota Original Year: 2020 Updated Model: Honda Updated Year: 2024 The Honda car of year 2024 is starting.Other Extensions