Basic use of reflection

Reflection enables programs running in the JVM to detect and modify runtime behavior

Reflection is to map various components of Java classes into corresponding Java classes through the java reflection API. After getting these classes, you can use them. For example, method, constructor, member variable, type, package, etc.

Basic method of reflection

There are three important classes in the java.lang.reflect package:

● Field: describes the domain of the class (member variable)

● Method: the Method (Method) describing the class

● Constructor: describes the Constructor (Constructor) of a class

For public domains (including superclass members):

● getFields

● getMethods

● getConstructors

For other domains (including private and protected members, excluding superclass members):

● gettDeclaredFields

● gettDeclaredMethods

● gettDeclaredConstructors

Three ways to obtain Class

        //1. class name
        Class pc1 = Person.class;
        //2. Object name. getClass()
        Class pc2 = person.getClass();
        //3.Class.forName("class name")
        Class pc3 = null;

Among them, the method of forName, which is closely related to reflection, obtains bytecode through class name. The first two are already loaded in the virtual machine. When the corresponding bytecode has not been loaded in the virtual machine, the forName method will be loaded dynamically; when it has been loaded, it will directly reuse the loaded one.

//Violence to break private authority
constructor.setAccessible(true);

Example

public class Person {

    public String name;
    private int age;

    public Person() {
    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;

        System.out.println("name:"+name);
        System.out.println("age:"+age);
    }

    public int getAge() {
        return age;
    }

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

    public void fun(String name) {
        System.out.println("name==============="+name);
    }
    private void fun_private(String name) {
        System.out.println("fun_private___name==========="+name);
    }
}
public static void main(String[] args) throws IllegalAccessException, InstantiationException {

        Person person = new Person("name:Coco", 22);

        //Three ways to obtain Class
        //1. class name
        Class pc1 = Person.class;
        //2. Object name. getClass()
        Class pc2 = person.getClass();
        //3.Class.forName("class name")
        Class pc3 = null;
        try {
            pc3 = Class.forName("com.bwie.reflectdemo1.reflect.Person");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }


        //Get the parameterless constructor and instantiate the class
        try {
            Constructor constructor = pc1.getDeclaredConstructor(null);
            //setAccessible is a switch that enables and disables access security checking. If it is not true, it can be accessed. If it is false, it cannot be accessed
            //            constructor.setAccessible(true);
            Person person1 = (Person) constructor.newInstance(null);
            person1.fun(person.name);

        } catch (Exception e) {
            e.printStackTrace();
        }

        //Get the parameter construction method, and the instance
        try {
            Constructor constructor = pc2.getConstructor(new Class[]{String.class, int.class});
            Person person2 = (Person) constructor.newInstance("Coco 1.8 meters", 22);
            person2.fun(person2.name);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //Get private method
        //Declared gets private protected, excluding superclass members
        try {
            //Get private method passed in method name and class
            Method method = pc3.getDeclaredMethod("fun_private", String.class);
            method.setAccessible(true);
            //Call the incoming instance, and parameters
            method.invoke(pc3.newInstance(), "Coco Get private");
        } catch (Exception e) {
            e.printStackTrace();
        }

        //Get member variable
        try {
            Person person1 = (Person) pc1.newInstance();
            Field age = pc1.getDeclaredField("age");
            age.setAccessible(true);
            age.set(person1,22);
            //Property to get the incoming object
            System.out.println(person1.getAge()+"---"+age.get(person1));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

    }

Print results

name:name:Coco
age:22
name===============name:Coco
name:Coco 1.8 meters
age:22
name===============Coco 1.8 meters
fun_private___name===========Coco Get private
22---22

Tags: Java jvm

Posted on Mon, 04 May 2020 16:15:01 -0700 by mgzee