Reflection mechanism learning record

Reflection

Reflection is regarded as the key of dynamic language. Reflection mechanism allows programs to obtain internal information of any class during execution by means of Reflection API, and directly manipulate the internal attributes and methods of any object.

Functions provided by Java reflection mechanism

Judge the class of any object at runtime;

Construct objects of any class at runtime.

Judge the member variables and methods of any class at runtime.

Call member variables and methods of any object at runtime.

Generate dynamic proxy.

Reflection-related API s

java.lang.Class represents a class

java.lang.reflect.Method represents the method of the class

java.lang.reflect.Field represents member variables of a class

Construction Method of Representative Class of java.lang.reflect.Constructor

......

 

4. Simple examples

public class Person {
    private String name;
    private int age;

    public Person() {
    }

    public Person(String name) {
        this.name = name;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public void show(){
        System.out.println("I am a person");
    }

    public void display(String nation){
        System.out.println("My nationality is"+nation);
    }

    @Override
    public String toString() {
        return "Person[name="+name+",age="+age;
    }
}



import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;

public class TestReflection {

    //Create an object of a class before reflection, and call its methods and attributes
    @Test
    public void test1(){
        Person person=new Person();
        person.setAge(10);
        person.setName("Xiao Ming");
        System.out.println(person);
        person.show();
        person.display("China");
    }

    //Create an object of a class before reflection and call its structure
    @Test
    public void test2() throws IllegalAccessException, InstantiationException, NoSuchFieldException {
        Class<Person> clazz=Person.class;
        //Establish clazz Corresponding runtime classes Person Objects of classes
        Person person=clazz.newInstance();
        System.out.println(person);
        Field f1=clazz.getField("name");
        f1.set(person,"Han Meimei");
        System.out.println(person);
    }
}

The following exception may be thrown when test2() is run:

No "name" attribute exists. The reason for this exception may be that the corresponding field does not exist, or the corresponding property is set to private, and private property, reflection can not be obtained, can be changed to public.

The revised phenomenon is that:

This is to invoke the specified attributes of the runtime class by reflection, public or private attributes can be invoked, and the specified methods can be invoked:

//Calling public attributes
Field f1=clazz.getField("name");
f1.set(person,
"Han Meimei"); System.out.println(person); //Call private attributes, getDeclaredField Calling declared properties, // setAccessible Setting Access Permissions Field f2=clazz.getDeclaredField("age"); f2.setAccessible(true); f2.set(person,20); System.out.println(person);
//Call the specified method of the runtime class by reflection
Method method1=clazz.getMethod("show");
method1.invoke(person);
Method method2=clazz.getMethod("display", String.class);//Add method parameter type
method2.invoke(person,"China");

 

Five

Class class

First, learn about Class classes, which are the source of reflection.

All classes inherit the getClass () method from the Object class, which returns a Class class, the runtime class of a particular object.

There are usually two ways to generate objects:

Normal way: Introduce the required "package class" name - > get instantiated objects through new instantiation - > Get instantiated objects

Reflection: Instantiate the object - > getClass () method - > Get the full package class name

Simply put: Reflection is to find the name of the class by object reflection, instantiate the package class, and vice versa, obtain the runtime class from the instance, and then reverse the structure of the class by the runtime class. An object can get its own properties, methods, constructors, interfaces and so on from the mirror.

Class itself is a class, Class objects can only be created by the system, a class in the JVM will only have a Class instance, a Class object corresponds to A. class file that has been loaded into the JVM, each class instance will remember which class instance generated by itself, so through Class you can get the integrity of a class. Structure.

 @Test
 public void test3(){
        Person person=new Person();
        //By runtime class object getClass(),Returns its runtime class
        Class clazz=person.getClass();
        System.out.println(clazz);
 }

Output results:

We create a class and generate the corresponding. class file by compiling (javac.exe).

Then load the. class file (java.exe, through the class loader of JVM)

After the. class file is loaded into memory, it is a runtime class stored in the cache, so the runtime class itself is a Class instance.

Each runtime class is loaded only once.

Tags: PHP Java jvm Junit Attribute

Posted on Sun, 28 Jul 2019 07:49:07 -0700 by sfarid