Java Basics: a deeper understanding of reflection

Time:2021-2-20

reflex

Reflection is the soul of frame! But first get the class type object corresponding to each bytecode file

1. Overview

The java reflection mechanism is based onrunning state For any class, you can know all the properties and methods of the class; for any object, you can call any of its methods and propertiesDynamic access to class information and dynamic call objectThe function of the method is called the reflection mechanism of Java language.

2. Summary

  • Reflection is to map various components of a Java class into Java objects one by one, so the application of reflection must depend on whether the target class is loaded, that is, first of all, it needs to be loaded by the row class to obtain the only instance of the class in Java Memory (method area)

  • Instances of the class class represent classes and interfaces in a running Java application. That is, there are more than n instances in the JVM, and each class has the class object. (including basic data types)

  • Class has no common constructor. The class object is automatically constructed by the Java virtual machine and by calling the defineclass method in the class loader. That is, we don’t need to deal with the creation by ourselves. The JVM has already created it for us.

3. Use of reflection

Java Basics: a deeper understanding of reflection3.1 three ways to get class object

Java Basics: a deeper understanding of reflection Object->getClass();

public class Main {
    public static void main(String[] args){
       Parent parent = new Parent();
        Class pclass = parent.getClass(); 
        //Because of the getClass method in the object class, because all classes inherit the object class. So call the object class to get the
    }
}
class Parent{
}

Java Basics: a deeper understanding of reflectionAny data type has a static class attribute

public class Main {
    public static void main(String[] args){
        Class pclass = Parent.class; 
        //Any data type (including the basic data type) has a "static" class attribute
    }
}
class Parent{
}

Java Basics: a deeper understanding of reflection Class.forName(String className)

public class Main {
    public static void main(String[] args){
        Class pclass = Class.forName("ddx.Main");
        //Static method through class: forname (string classname) (commonly used)
    }
}
class Parent{
}

Java Basics: a deeper understanding of reflection The third method is commonly used in the three methods. When the first object is available, what do you want to do with reflection. The second is the package that needs to import classes. If the dependency is too strong, the compilation error will be thrown if the package is not imported. Generally, there are three methods. A string can be passed in or written in the configuration file.

2. Get the construction method by reflection and use:

package fanshe;

public class Student {

    //---------------Construction method-------------------
    //(default construction method)
    Student(String str){
        System.out.println(Construction method of "(default) =" + str);
    }

    //Nonparametric construction method
    public Student(){
        System.out.println("The public, parameterless construction method was called and executed... ");
    }

    //There is a construction method of parameters
    public Student(char name){
        System.out.println(Name: + name);
    }

    //Construction method with multiple parameters
    public Student(String name ,int age){
        System.out.println(Name:+name+Age:+ age);//There is a problem with the efficiency of the implementation of this plan, which will be solved later.
    }

    //Protected construction method
    protected Student(boolean n){
        System.out.println("Protected constructor n =" + n);
    }

    //Private construction method
    private Student(int age){
        System.out.println(Private constructor age:+ age);
    }

}

Test category:

package fanshe;

import java.lang.reflect.Constructor;


/*
public class Constructors {

    public static void main(String[] args) throws Exception {
        //1. Load class object
        Class clazz = Class.forName("fanshe.Student");


        //2. Get all public construction methods
        System.out.println("All public construction methods");
        Constructor[] conArray = clazz.getConstructors();
        for(Constructor c : conArray){
            System.out.println(c);
        }


        System.out.println("All construction methods (including private, protected, default, and public) * *");
        conArray = clazz.getDeclaredConstructors();
        for(Constructor c : conArray){
            System.out.println(c);
        }

        System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * * * * *);
        Constructor con = clazz.getConstructor(null);
        //1> Because it is a parameterless construction method, the type is null. It is OK not to write: what you need here is a parameter type, remember that it is a type
        //2> , returns the class object that describes the parameterless constructor.

        System.out.println("con = " + con);
        //Call constructor
        Object obj = con.newInstance();
    //    System.out.println("obj = " + obj);
    //    Student stu = (Student)obj;

        System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * * * *);
        con = clazz.getDeclaredConstructor(char.class);
        System.out.println(con);
        //Call constructor
        con.setAccessible(true);//Brute force access (ignore access modifier)
        obj = con.newInstance('male ');
    }

}

4. Get member variables and call


package fanshe.field;
import java.lang.reflect.Field;
/*
public class Fields {

        public static void main(String[] args) throws Exception {
            //1. Get class object
            Class stuClass = Class.forName("fanshe.field.Student");
            //2. Get field
            System.out.println("Get all the public fields ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ *");
            Field[] fieldArray = stuClass.getFields();
            for(Field f : fieldArray){
                System.out.println(f);
            }
            System.out.println("Get all the fields (including private, protected and default) *");
            fieldArray = stuClass.getDeclaredFields();
            for(Field f : fieldArray){
                System.out.println(f);
            }
            System.out.println("Get public field * * and call ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ *");
            Field f = stuClass.getField("name");
            System.out.println(f);
            //Get an object
            Object obj = stuClass.getConstructor().newInstance();//Generate Student object -- "student student = new student();
            //Set a value for the field
            f.set(obj, "Andy Lau");//Assign a value to the name attribute in the student object -- " stu.name  ="Andy Lau"
            //Verification
            Student stu = (Student)obj;
            System.out.println(Verify Name: + stu.name);


            System.out.println("Get private field and call");
            f = stuClass.getDeclaredField("phoneNum");
            System.out.println(f);
            f.setAccessible(true);//Violent reflexes, lifting private restrictions
            f.set(obj, "18888889999");
            System.out.println(Verify phone: + stu);

        }
    }

4. Gets the member method and calls the

5. Reflection main method

This work adoptsCC agreementReprint must indicate the author and the link of this article

Recommended Today

Background management system menu management module

1 menu management page design 1.1 business design Menu management, also known as resource management, is the external manifestation of system resources. This module is mainly to add, modify, query and delete the menu. CREATE TABLE `sys_menus` ( `id` int(11) NOT NULL AUTO_INCREMENT, `Name ` varchar (50) default null comment ‘resource name’, `URL ` varchar […]