Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Reflection

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:

Workflow

  1. Obtain the Class object: First obtain the target class's Class object.
  2. Obtain member information: Through Class object, with which you can obtain the class's fields, methods, constructors, and other information.
  3. 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

- `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

- `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

- `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

- `newInstance(Object... initargs)`: Creates a new instance using the specified constructor parameters. - `getParameterTypes()`: Gets the parameter types of the constructor. - `getModifiers()`: Gets 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.