About java reflection

1. The reflection mechanism is to know all the properties and methods of any class in the running state.

2. Reflection is a mechanism that can obtain class information when a class is running, and can obtain class information that cannot be obtained at compile time.

3. Any method and property of any object can be called.

4. Because the Class information is saved in the Class object, which is dynamically loaded by the Class loader when the program is running.

5. When the Class loader loads and runs the Class, the function of dynamically obtaining the information of the Class object and dynamically operating the properties and methods of the Class object is called the reflection mechanism of Java voice.

1. Decompile:. class - >. Java.

2. Access properties, methods, construction methods, etc. in Java objects through reflection mechanism.

Reflection principle
Principle of java reflection: the execution of Java classes needs to go through the following processes,

Class loading

Compilation: the. java file is compiled to generate a. class bytecode file

Loading: the class loader is responsible for reading the binary bytes of a class according to the fully qualified name of the class, streaming them into the JVM, storing them in the method area of the runtime memory area, and then converting them into a java.lang.Class object instance corresponding to the target type

Connecting: subdividing three steps

Verification: format (class file specification) semantics (whether the final class has subclasses) operation

Preparation: static variables are assigned initial values and memory space, and the memory space modified by final is directly assigned original values. This is not the initial value specified by the user.

Resolution: convert symbolic references to direct references and assign addresses

Initialization: if there is a parent class, first initialize the parent class, and then initialize itself; Execute the static modification code once. If it is a static variable, the original initial value will be overwritten with the value specified by the user; If it is a code block, perform the operation once.

Java reflection uses the. Class file loaded into the jvm in step 2 above to operate The class file contains all the information of Java classes. When you don't know the specific information of a class, you can use reflection to obtain the class and then carry out various operations.

Java reflection is to know all the properties and methods of any class in the running state; For any object, you can call any of its methods and properties; And can change its properties.

In conclusion, reflection is to map various components of Java classes into Java objects one by one, and can be operated.

Three ways to get class

Get class

Class main methods
getName(): get the full name of the class.

getFields(): get the public type attribute of the class.

Getdeclaraedfields(): get all the properties of the class. Includes private declared and inherited classes

getMethods(): get the public type method of the class.

Getdeclaraedmethods(): get all the methods of the class. Includes private declared and inherited classes

getMethod(String name, Class[] parameterTypes): get the specific method of the class. The name parameter specifies the name of the method, and the parameterTypes parameter specifies the parameter type of the method.

getConstructors(): get the constructor of the public type of the class.

getConstructor(Class[] parameterTypes): get the specific constructor of the class. The parameterTypes parameter specifies the parameter type of the constructor.

newInstance(): create an object of this class through the construction method of the class.

Code test method:

Person.java Class:

package reflect;
import java.util.Date;
 * @author pine
public class Person {
    private String username;
    private int age;
    private Date birthDay;
    public String nick;
    public Person(String username){
        this.username = username;
    public Person(){
    public Person(String username,int age){
        this.username = username;
        this.age = age;
    public String getNick() {
        return nick;
    public void setNick(String nick) {
        this.nick = nick;
    public String getUsername() {
        return username;
    public void setUsername(String username) {
        this.username = username;
    public int getAge() {
        return age;
    public void setAge(int age) {
        this.age = age;
    public Date getBirthDay() {
        return birthDay;
    public void setBirthDay(Date birthDay) {
        this.birthDay = birthDay;
    private void sayHello(){
        System.out.println("person sayHello ---");
    public void workIng(){
        System.out.println("person work ing ---");
    public String toString() {
        return "Person{" +
                "username='" + username + '\'' +
                ", age=" + age +
                ", birthDay=" + birthDay +
                ", nick='" + nick + '\'' +

ReflectTest.java class:

package reflect;
import com.alibaba.fastjson.JSON;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
 * reflex
 * @author anzy
public class ReflectTest {
    public static void main(String[] args) {
//       testClassEqual();
    public static void testClassEqual(){
        //1. Object calls the getClass() method to get it. It is usually used in: for example, you pass an object
        //  Type of object, and I don't know what kind of class you are, use this method
        Person person = new Person();
        Class c1 = person.getClass();
        //2. Obtained by class name. Class, this method is the most secure and reliable with high performance
        //  This means that any class has an implicit static member variable class
        Class c2 = Person.class;
        //3. It is obtained through the forName() static method of Class object. It is used most,
        //   However, ClassNotFoundException may be thrown
        Class c3 = null;
        try {
            c3 = Class.forName("reflect.Person");
        } catch (ClassNotFoundException e) {
    public static void testMethodClass(){
        Class c3 = null;
        try {
            c3 = Class.forName("reflect.Person");
        } catch (ClassNotFoundException e) {
        System.out.println("c3.getName():" + c3.getName());
        // Get the public type property of the class.
        Field[] fields = c3.getFields();
        System.out.println("c3.getFields():" + JSON.toJSON(fields));
        //Output result: C3. Getfields(): [{"accessible": false, "declaraedannotations": [], "synthetic": false, "annotatedtype":
        // {"declaredAnnotations":[],"annotations":[],"type":"java.lang.String"},
        // "enumConstant":false,"name":"nick","annotations":[],"genericType":"java.lang.String",
        // "modifiers":1,"type":"java.lang.String","declaringClass":"reflect.Person"}]
        // As can be seen from the output result, only the nick public attribute in the Person class is obtained.
        Field[] fieldsAll = c3.getDeclaredFields();
        System.out.println("c3.getDeclaredFields():" + JSON.toJSON(fieldsAll));
        try {
            // Only public methods can be obtained, and an error will be reported when obtaining private: java.lang.NoSuchMethodException: reflect.Person.sayHello()
            Method method = c3.getMethod("workIng",null);
            System.out.println("method: " + method);
            Method[] methods = c3.getMethods();
            System.out.println("methods: " + methods);
            // Both public and private methods can be obtained
            Method declaredMethod = c3.getDeclaredMethod("sayHello",null);
            System.out.println("declaredMethod: " + declaredMethod);
            Method[] declaredMethods = c3.getDeclaredMethods();
            System.out.println("declaredMethods: " + declaredMethods);
            // Get constructor
            Constructor<Person> constructors[] = c3.getConstructors();
            System.out.println("constructors: " + constructors);
            // JSON.toJSON(constructors) will report an error and the stack overflows. Exception in thread "main" java.lang.StackOverflowError
//            System.out.println("constructors: " + JSON.toJSON(constructors));
            // Create an object of this class through the construction method of the class.
            Person person = constructors[0].newInstance("pine",1);
            System.out.println("person: " + person);
        } catch (NoSuchMethodException e) {
        }catch (InstantiationException e) {
        } catch (IllegalAccessException e) {
        } catch (InvocationTargetException e) {

C3. Results obtained by getmethod():

C3. Results obtained by getmethod():

C3. The result obtained by getdeclaredmethods()

C3. The result obtained by getdeclaredmethods()

Two comparisons can be found:

getMethods() can get the public method in the Object class.

Getdeclaraedmethods() failed to get.

Let's think about the relationship between common classes and objects:

The Object class is the parent class of all java classes. For ordinary java classes, even if they are not declared, they inherit the Object class by default. Typically, the toString() method in the Object class can be used.

Functions that can be realized by Class
1. Judge which class the object belongs to

Person person = new Person();

Class class2= person.getClass();

System.out.println("class2: "+class2);

Output: class2: class reflect.Person

2 get class information

Class class1 = Person.class;

Method[] methods = class1.getMethods();

Method[] declaredMethods = class1.getDeclaredMethods();

Field[] declaredFields = class1.getDeclaredFields();

3 build object

Person person = new Person();

Class class2= person.getClass();

Object o = class2.newInstance();

//Use instanceof to judge before strong turn

if(o instanceof Person){
((Person) o).workIng();


4 dynamic execution method

Class class1 = Class.forName("reflect.Person");

Method work = class1.getDeclaredMethod("work");

Person person = new Person();


5 dynamic operation properties

Class class1 = Class.forName("reflect.Person");

Person person = new Person();

Field field = class1.getDeclaredField("username");


6 dynamic agent

Tags: Java

Posted on Fri, 08 Oct 2021 15:16:41 -0400 by Grimloch