Java Reflection Concept and Using Example Code

  • 2021-12-11 17:54:56
  • OfStack

Preface to the table of contents Reflex Basic data preparation
Creating Objects Based on Reflection
Getting Objects in Reflection
Get the property in the class
Gets the constructor method in the class
Get the method in the class
Conclusion

Preface

Hello, everyone, on the first day after Ruixue, everyone on Monday is looking forward to the coming of Friday this week. I believe many friends did two things last weekend, enjoying snow and watching EDG. Haha, let's get down to business. Let's talk about reflection today, which is often used in java.

Reflex

I believe that those who have just come into contact with Java will definitely ask what is reflection in the first sentence. What does reflex do? Why use reflection? First of all, reflection is one of the characteristics of Java. In the process of running, Java program in the project automatically identifies and creates corresponding classes, and can dynamically call class attributes, construction methods and methods in classes. 1 sentence description: In the program, different classes and attributes can be dynamically called to perform specific operations.

Reflection is used in many frameworks because it can dynamically load desired objects at runtime. This time, in order to have a good understanding of reflection, we will introduce several aspects: creating objects based on reflection, obtaining objects in reflection, obtaining attributes in classes, obtaining construction methods in classes, and obtaining methods in classes.

Basic data preparation

For the convenience of demonstration, a basic object class is created. And based on him, this introduction is made. The demonstration class JueJinUser created is as follows, which contains four attributes, namely get and set methods, and toString methods. No constructor is created, and the related reflection methods automatically created by reflection are described below.


public class JueJinUser {
    private Integer id;

    private String name;

    private String title;

    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "JueJinUser{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", title='" + title + '\'' +
                ", age=" + age +
                '}';
    }
}

Creating Objects Based on Reflection

There are two main ways to create a class object based on reflection: the first is through the class object's newInstance () method, and the second is through the newInstance () method in the constructor.

newInstance () method of class object

The newInstance () method of the class object is created as follows:


       Class class = JueJinUser.class;
       JueJinUser jueJinUseByClass = (JueJinUser) class.newInstance();

newInstance () method of constructor


        Class jueJinUserClass = JueJinUser.class;
        Constructor constructor = jueJinUserClass.getConstructor();
        JueJinUser jueJinUserByConstructor = (JueJinUser) constructor.newInstance();

It should be noted that the first newInstance () method based on class objects can only be a parametric construction method, while the second newInstance () method based on constructor can have parametric construction method and parametric construction method, which is more flexible.

Getting Objects in Reflection

There are three ways to get reflection objects: Class. forName, class method, and getClass () method. Obtain the reflection of the object method we use in the project or more, I believe we are no strangers.

Class.forName


    Class clzForName = Class.forName("com.example.demo.module.JueJinUser");

. class method


    Class clzForClass =JueJinUserString.class;
        

getClass () method


    JueJinUser JueJinUser = new JueJinUser();
    Class clzNewObject = str.getClass();

Get the property in the class

Through the methods of getFields and getDeclaredFields, the attribute information in the class can be obtained, in which getFields can obtain the public attribute value in the class, while the method of getDeclaredFields can obtain the attribute information in all classes, but cannot obtain the information of the parent class. The format is as follows:


        Class clz = JueJinUser.class;
        Field[] fields = clz.getFields();
        System.out.println("--- getFields start ---");
        for (Field field : fields) {
            System.out.println(field.getName());
        }
        System.out.println("--- getFields end ---");


        System.out.println("--- getDeclaredFields start ---");
        Field[] declaredFields = clz.getDeclaredFields();
        for (Field field : declaredFields) {
            System.out.println(field.getName());
        }
        System.out.println("--- etDeclaredFields end ---");

Gets the constructor method in the class

The methods of getConstructors and getDeclaredConstructors can obtain the constructor information in the class, in which getConstructors can obtain the constructor information in the class, while the methods of getDeclaredConstructors can obtain the constructor information in all classes, but cannot obtain the constructor information of the parent class. The format is as follows:


     System.out.println("--- getConstructors start ---");
        Constructor[] constructors = clz.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor.getName());
        }
        System.out.println("--- getConstructors end ---");

        System.out.println("---getDeclaredConstructors start---");
        Constructor[] declaredConstructors = clz.getDeclaredConstructors();
        for (Constructor constructor : declaredConstructors) {
            System.out.println(constructor.getName());
        }
        System.out.println("---getDeclaredConstructors end---");

Get the method in the class

The methods of getMethods and getDeclaredMethods can obtain the constructor information in the class, in which getMethods can obtain the constructor information in the class, while the methods of getDeclaredMethods can obtain the methods in all classes, but cannot obtain the method information of the parent class. The format is as follows:


     System.out.println("--- getMethods start ---");
        Method[] methods = clz.getMethods();
        for (Method method : methods) {
            System.out.println(method.getName());
        }
        System.out.println("--- getMethods end ---");


        System.out.println("--- getDeclaredMethods start---");
        Method[] declaredMethods = clz.getDeclaredMethods();
        for (Method method : declaredMethods) {
            System.out.println(method.getName());
        }
        System.out.println("--- getDeclaredMethods end ---");

Conclusion


Related articles: