8, Reflection mechanism of Java

Keywords: Java Attribute jvm

1. Definition of reflection

Java reflection mechanism is a reflection mechanism of Java language that can know all the properties and methods of any class in the running state of a program, and can call any method and property of any object. This kind of dynamic information acquisition and function of dynamically calling object methods is called Java language reflection mechanism.

In short, the Java reflection mechanism is to encapsulate the properties, methods and constructors of a class into objects for the use of callers.

2. Why use reflection

Before we understand why reflection is used, let's first look at an example:

In order to standardize the action of instantiating specific animals, we assign the action to an example chemical factory, which will instantiate the corresponding animal object according to the user's requirements.

/**
 * Animal
 */
public abstract class Animal {
    /**
     * How animals eat
     */
    public abstract void eat();
}

/**
 * cat
 */
public class Cat extends Animal {
    @Override
    public void eat() {
        System.out.println("Cats eat fish.");
    }
}

/**
 * Dog
 */
public class Dog extends Animal{
    @Override
    public void eat() {
        System.out.println("Dogs eat bones.");
    }
}

public class Factory {

    //Instanced object
    public static Animal getInstance(String className){
        Animal animal = null;
        if(className.equals("Dog")){
            animal = new Dog();
        }else if(className.equals("Cat")){
            animal = new Cat();
        }
        return animal;
    }
}

Next, we use this factory to create an instantiated object of the cat and call the method it eats.

    public static void main(String[] args) {

        Animal animal = Factory.getInstance("Cat");
        animal.eat();
        
    }

    //Result: cat eats fish

Although the unified specification of instantiation action is implemented through this method, if we declare a new animal class hamster at this time, then the code in Factory must add the conditional judgment of hamster. In this way, every time we declare a new animal class, we have to change the code in the Factory once. Isn't that troublesome? At this point, Java's reflection mechanism comes in handy.

In fact, the most important use of Java reflection mechanism is to develop various general frameworks. By using the framework, developers can greatly reduce the amount of code, improve development efficiency, and improve product performance.

3. The stage of Java code in the computer

① javac compiles. java files into. class bytecode files.

② The. Class file is converted from a class loader to a class object.

③ Create objects in memory through Class objects.

4. Use of Class

Java's reflection mechanisms are all implemented by using the generic Class class, so we need to learn the Class API for how to use the reflection mechanism.

public class Person {

    private String name;//Private attributes
    public Integer age;//Public attribute

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

    public String getName() {
        return name;
    }

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

    public void method(String param) {
        System.out.println("Parameters:" + param + "   Method executed");
    }
}

(1) Three ways to get Class objects

Class class has no public constructor. Class objects are constructed by JVM calling class loader. Java code has gone through three stages in the computer, so for each stage, there is a way to turn the Java code of the corresponding stage into a class object.

① Source source phase: find the bytecode file (. Class file) and load it into memory to create a class object.

static Class<?> forName(String className)
Returns the Class object associated with a Class or interface with the given string name.
    public static void main(String[] args) {
        try {
            //The Class obtained by this method does not determine its generics, so it is accepted by wildcards
            Class<?> aClass = Class.forName("com.java.day01.Person");//Get Class object
            System.out.println(aClass);
        } catch (ClassNotFoundException e) {
            System.out.println("This class does not exist");
        }

    }

    //Result:

    class com.java.day01.Person

② Class object stage: obtain the class object through the class attribute.

    public static void main(String[] args) {

        Class<?> aClass = Person.class;
        System.out.println(aClass);

    }

    //The result is:

    class com.java.day01.Person

③ Runtime runtime stage: obtained by getClass() method of base class Object class.

    public static void main(String[] args) {
        Person person = new Person("Zhang San");
        Class<?> aClass = person.getClass();
        System.out.println(aClass);
    }

    //Result:

    class com.java.day01.Person

(2) getName() method and toString() method

 String

getName()
Returns the name of the entity (Class, interface, array Class, basic type or void) represented by this Class object in the form of String.

 String toString()
Converts an object to a string. The string is represented by the string "class" or "interface" followed by a space, followed by the fully qualified name of the class
    public static void main(String[] args) throws NoSuchMethodException,     
        IllegalAccessException, InvocationTargetException, InstantiationException {

        Class<?> aClass = Person.class;

        String s1 = aClass.getName();//Get class name
        String s2 = aClass.toString();//Print class information

        System.out.println(s1);
        System.out.println(s2);
    }

    //The result is:

    com.java.day01.Person
    class com.java.day01.Person

(3) isInstance() method and newInstance() method

boolean isInstance(Object obj)
Determines whether the specified Object is compatible with the Object assignment represented by this Class. This method is the dynamic equivalent of the instanceof operator.
 T newInstance()
Create a new instance of the Class represented by this Class object. It is like instantiating the Class (empty parameter construction) with a new expression of an empty parameter list.
    public static void main(String[] args) throws NoSuchMethodException, 
        IllegalAccessException, InvocationTargetException, InstantiationException {

        Class<?> aClass = Person.class;

        //A new Person instance can only call the null parameter constructor
        //Using Constructor object to create instance (with parameter construction) instead of this method
        Object o = aClass.newInstance();

        Person person = null;

        //Determine whether the Object is compatible with Class A
        if(aClass.isInstance(o)){
            person = (Person)o;//Downward transformation
        }

        //instanceof
        if(o instanceof Person){
            person = (Person)o;
        }
    }

 

21 original articles published, 10 praised, 846 visited
Private letter follow

Posted by phppucci on Sun, 02 Feb 2020 00:38:16 -0800