What is the use of Java reflection?

reflection

All operations on Class objects are based on reflection.

Introduction

Reflection can obtain and use member variables, member methods, construction methods, etc. of a class during the running of the program.

The reflection operates on the Class type object, and the member variables, construction methods, member methods and other information in the class are obtained through this Class type object.

Obtain

1. Object instance.getClass()

2. Class name.Class()

3.Class.forName(String className)

Note: A class has only one Class type object, no matter how it is obtained, the same Class is obtained.

​ All data types have class attributes, including basic types.

Common methods in Class

Get the class name:

​ – getName() Get the name of the class (fully qualified name)

​ – getSimpleName() Get the simple class name (excluding package name, not fully qualified name)

Get member variables:

​ – getFields() Get all the member variables in the class

​-Field getField (name of member variable) Get the specified member variable

​ set(Object obj, Object value) obj sets the value of which object member variable value is set to what value.

​ get(Object obj) Get the value of the member variable of which object

Get the construction method:

​ – getConstructors() Get all the constructors in the class

​ – getConstructor (parameters required for the parameter construction) to obtain the construction method specified in a class

Get member method:

​ – getMethods() Get all the member methods in the class

​-Method getMethod (method name, the method parameter list) Get the specified method object!!!

​ Method means member method

​ Object invoke(object obj, Object… args) The soul of dynamic agent. Method object!!!

Get the instance object:

​ – newInstance() creates an instance object (by default, the object is created using empty parameter construction)

​ – newInstance (parameters required to construct parameters) to create an instance object

Reflection step

1. Get the Class object of the class.

2. Get the content of the class (member variables, construction methods, member methods) through the Class object.

3. Use this content.

Guess you like

Origin blog.csdn.net/numbbe/article/details/109280106