“This is the 8th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”

preface

Hello everyone, the first day after the snow, every Monday everyone is looking forward to the coming of this Friday. I believe many friends last weekend only two things, watching snow and WATCHING EDG. Haha, let’s get started. Today we will talk about reflection, which is often used in Java.

reflection

If you are new to Java, what is reflection? What does reflection do? Why use reflection? First of all, reflection is one of the characteristics of Java. In the process of running, The Java program in the project automatically identifies and creates the corresponding class, and can dynamically call the attributes, constructors and methods of the class. A program that dynamically calls different classes and properties to perform specific operations.

Reflection is used in many frameworks because of its ability to dynamically load objects at run time. This time in order to have a good understanding of reflection, will be based on reflection to create an object, get the object in reflection, get the attribute in class, get the constructor in class, get the method in class several aspects are introduced, the following began to enter the topic.

Basic Data Preparation

For demonstration purposes, a basic object class is created. And this introduction is based on him. The demo class JueJinUser is created as follows. It contains four properties, including get and set methods, and toString methods. No constructors are created.

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 +
                '} '; }}Copy the code

Create objects based on reflection

There are two main ways to create class objects based on reflection: first, through the newInstance() method of class objects, and second, through the newInstance() method of constructors.

Class object newInstance() method

Class objects create newInstance() as follows:

       Class class = JueJinUser.class;
       JueJinUser jueJinUseByClass = (JueJinUser) class.newInstance();
Copy the code
Constructor newInstance() method
        Class jueJinUserClass = JueJinUser.class;
        Constructor constructor = jueJinUserClass.getConstructor();
        JueJinUser jueJinUserByConstructor = (JueJinUser) constructor.newInstance();
Copy the code

It should be noted that the first method of creating newInstance() based on class objects can only be a no-parameter constructor, while the second method of creating newInstance() based on constructors can have both parametric constructors and no-parameter constructors, which is more flexible.

Gets the object in the reflection

There are three ways to get a reflection object: class.forname,.class, and getClass(). The method of obtaining objects in reflection is used more in the project, I believe everyone is familiar with.

Class.forName
    Class clzForName = Class.forName("com.example.demo.module.JueJinUser");
Copy the code
.class method
    Class clzForClass =JueJinUserString.class;
        
Copy the code
GetClass () method
    JueJinUser JueJinUser = new JueJinUser();
    Class clzNewObject = str.getClass();
Copy the code

Gets an attribute in a class

The methods getFields and getDeclaredFields can obtain the attribute information of the class. GetFields can obtain the public attribute value of the class, while getDeclaredFields can obtain the attribute information of 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 ---");
Copy the code

Gets a constructor in a class

GetConstructors and getDeclaredConstructors get constructor information from a class, and getDeclaredConstructors get constructor information from a class. Gets constructors in all classes, but cannot get constructor information for 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---");
Copy the code

Gets a method in a class

Through getMethods and getDeclaredMethods, constructor information in a class can be obtained. GetMethods can obtain constructor information in a class, while getDeclaredMethods can obtain methods in all classes. However, the method information of the parent class cannot be obtained. 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 ---");
Copy the code

conclusion

Well, the above is a simple introduction of reflection, thank you for reading, I hope you like it, if it is helpful to you, welcome to like collection. If there are shortcomings, welcome comments and corrections. See you next time.

About the author: [Little Ajie] a love tinkering with the program ape, JAVA developers and enthusiasts. Public number [Java full stack architect] maintainer, welcome to pay attention to reading communication.