Java Reflection
Java Reflection is a powerful feature that allows a program to query, access, and modify information about classes, interfaces, fields, and methods at runtime. Reflection provides a capability to dynamically manipulate classes, which is widely used in many frameworks and libraries, such as the dependency injection of the Spring framework.
Reflection API
Java's Reflection API provides a series of classes and interfaces to operate on Class objects. The main classes include:
java.lang.Class: Represents an object of a class. Provides methods to obtain the fields, methods, constructors, etc. of the class.java.lang.reflect.Field: Represents a field (attribute) of a class. Provides the ability to access and modify fields.java.lang.reflect.Method: Represents a method of a class. Provides the ability to invoke methods.java.lang.reflect.Constructor: Represents a constructor of a class. Provides the ability to create objects.
Workflow
- Obtain the
Classobject: First obtain the target class'sClassobject. - Obtain member information: Through
Classobject, with which you can obtain the class's fields, methods, constructors, and other information. - Manipulate members: Through the Reflection API, you can read and modify field values, invoke methods, and create objects.
The following are the basic usage of Java Reflection and its common applications.
1. Obtain a Class object
Each class has an associated Class object in the JVM. You can obtain the Class object in the following ways:
**Via class literal**
Class> clazz = String.class;
Via object instance:
String str = "Hello";
Class> clazz = str.getClass();
**Via the Class.forName() method:**
Class> clazz = Class.forName("java.lang.String");
2. Create an object
You can use reflection to create objects dynamically:
Class> clazz = Class.forName("java.lang.String");
Object obj = clazz.getDeclaredConstructor().newInstance();
3. Access fields
You can access and modify class fields via reflection:
Class> clazz = Person.class;
Field field = clazz.getDeclaredField("name");
field.setAccessible(true); // 如果字段是私有的,需要设置为可访问
Object value = field.get(personInstance); // 获取字段值
field.set(personInstance, "New Name"); // 设置字段值
4. Invoke methods
You can invoke class methods via 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. Obtain constructors
You can obtain and invoke constructors via reflection:
Class> clazz = Person.class;
Constructor> constructor = clazz.getConstructor(String.class, int.class);
Object obj = constructor.newInstance("John", 30);
6. Obtain interfaces and parent class
You can obtain the interfaces implemented by a class and its parent class via reflection:
Class> clazz = Person.class;
// Get all interfaces
Class>[] interfaces = clazz.getInterfaces();
for (Class> i : interfaces) {
System.out.println("Interface: " + i.getName());
}
// Get parent class
Class> superClass = clazz.getSuperclass();
System.out.println("Superclass: " + superClass.getName());
The following is a complete example demonstrating how to use reflection to create objects, access fields, and invoke methods:
Example
import
java.lang.reflect.Constructor
;
import
java.lang.reflect.Field
;
import
java.lang.reflect.Method
;
public
class
ReflectionExample
{
public
static
void
main
(
String
[
]
args
)
throws
Exception
{
// Obtain 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 run the above code; the output is:
Name: John
Updated Name: Doe
Doe says: World
java.lang.reflect
java.lang.reflect is the core package of the Java Reflection mechanism, providing classes and interfaces for operating on 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 are java.lang.reflect Detailed introduction of the main classes and interfaces in the package:
1. Class class
- Function: Represents an object of a class, providing methods to obtain class information, such as fields, methods, constructors, etc.
- Main methods:
getFields(): Obtain all public fields.getDeclaredFields(): Obtain all declared fields, including private fields.getMethods(): Obtain all public methods.getDeclaredMethods(): Obtain all declared methods, including private methods.getConstructors(): Obtain all public constructors.getDeclaredConstructors(): Obtain all declared constructors, including private constructors.getSuperclass(): Obtain the parent class of the class.getInterfaces(): Obtain all interfaces implemented by the class.
2. Field class
- Function: Represents a field (attribute) of a class, providing methods to access and modify field values.
- Main methods:
get(Object obj): Obtain the field value of the specified object.set(Object obj, Object value): Set the field value of the specified object.getType(): Obtain the data type of the field.getModifiers(): Obtain the modifiers of the field (such as public, private).
3. Method class
- Function: Represents a method of a class, providing the ability to invoke methods.
- Main methods:
invoke(Object obj, Object... args): Invoke the method of the specified object.getReturnType(): Obtain the return type of the method.getParameterTypes(): Obtain the parameter types of the method.getModifiers(): Obtain the modifiers of the method (such as public, private).
4. Constructor class
- Function: Represents a constructor of a class, providing 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 how to use java.lang.reflect Example of reflection operations using the package:
Example
import
java.lang.reflect.Field
;
import
java.lang.reflect.Method
;
import
java.lang.reflect.Constructor
;
public
class
ReflectionExample
{
public
static
void
main
(
String
[
]
args
)
throws
Exception
{
// Obtain 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 to be 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 run the above code; the output is:
Original Model: Toyota
Original Year: 2020
Updated Model: Honda
Updated Year: 2024
The Honda car of year 2024 is starting.