day24 class loader & reflection of note operation instructions

1. Class loader
1.1 class loading [understanding]
Description of class loading
When a program wants to use a class, if the class has not been loaded into memory, the system will load the class, connect the class, and initialize the class
Initialize the class by initializing these three steps. If there are no accidents, the JVM will complete these three steps in succession, so sometimes
These three steps are collectively referred to as class loading or class initialization
Class loading
It means reading the class file into memory and creating a java.lang.Class object for it
When any class is used, the system will create a java.lang.Class object for it
Class connection
Verification phase: used to verify whether the loaded class has the correct internal structure and is consistent with other classes
Preparation phase: allocate memory for class variables of the class and set the default initialization value
Parsing phase: replace the symbol reference in the binary data of the class with a direct reference
Class initialization
In this stage, class variables are mainly initialized
Class initialization steps
If the class has not been loaded and connected, the program loads and connects the class first
If the direct parent of this class has not been initialized, initialize its direct parent first
If there are initialization statements in the class, the system executes these initialization statements in turn
Note: when executing step 2, the system also follows initialization steps 1-3 for the direct parent class
Class initialization time
Create an instance of a class
Call the class method of the class
Access or assign a value to a class variable of a class or interface
Use reflection to force the creation of java.lang.Class objects corresponding to a class or interface
Initializes a subclass of a class
Directly use the java.exe command to run a main class
Class 1.2 loader [understanding]
1.2.1 function of class 1 loader
Be responsible for loading the. Class file into memory and generating the corresponding java.lang.Class object for it. Although we don't have to care too much about class loaders
But understanding this mechanism, we can better understand the operation of the program!
1.2.2 class loading mechanism of JVM
Overall responsibility: when a Class loader is responsible for loading a Class, other classes that the Class depends on and references will also be loaded by the Class
The loader is responsible for loading unless the display uses another class loader to load
Parent Class delegation: when a Class loader is responsible for loading a Class, first let the parent Class loader try to load the Class, only in the parent Class loader
Attempt to load the class from your own classpath only when the class cannot be loaded
Caching mechanism: ensure that all loaded classes will be cached. When the program needs to use a Class object, the Class loader searches the cache first
Retrieve the Class. Only when the Class object does not exist in the cache, the system will read the binary data corresponding to the Class and convert it into
Class object, stored in cache
1.2.3 built in class loader in Java
Bootstrap class loader: it is the built-in class loader of the virtual machine. It is usually expressed as null and has no parent null
Platform class loader: the platform class loader can see all platform classes, including Java classes defined by the platform class loader or its ancestors
SE platform API, its implementation class and JDK specific runtime class
System class loader: it is also called application class loader, which is different from platform class loader. System class loaders are commonly used to define the
Use program classpath, module path and classes on JDK specific tools
Inheritance relationship of class loader: the parent loader of System is Platform, and the parent loader of Platform is Bootstrap
1.2.4 two methods in classloader

Method classification

Method nameexplain
static ClassLoader getSystemClassLoader()Returns the system class loader used for delegation
ClassLoader getParent()Returns the parent loader for delegation


Sample code

public class ClassLoaderDemo {
public static void main(String[] args) {
//static ClassLoader getSystemClassLoader(): returns the system class loader used for delegation
ClassLoader c = ClassLoader.getSystemClassLoader();
System.out.println(c); //AppClassLoader
//ClassLoader getParent(): returns the parent class loader for delegation
ClassLoader c2 = c.getParent();
System.out.println(c2); //PlatformClassLoader
ClassLoader c3 = c2.getParent();
System.out.println(c3); //null
}
}

result:


2. Reflection
2.1 overview of reflection [understanding]
It refers to obtaining the variable and method information of a class at run time. Then create an object through the obtained information and call a mechanism of the method.
Because of this dynamic, it can greatly enhance the flexibility of the program. The program does not need to be determined at the compilation time, and can still be extended at the run time
2.2 three methods of obtaining Class objects [ application ]
2.2.1 classification of three methods
class name. class attribute
Object name. getClass() method
Class. Forname (full class name) method
2.2.2 example code

public class ReflectDemo {
public static void main(String[] args) throws ClassNotFoundException {
//Use the class attribute of the class to get the class object corresponding to the class
Class<Student> c1 = Student.class;
System.out.println(c1);
Class<Student> c2 = Student.class;
System.out.println(c1 == c2);
System.out.println("--------");
//Call the getClass() method of the object to return the Class object corresponding to the Class to which the object belongs
Student s = new Student();
Class<? extends Student> c3 = s.getClass();
System.out.println(c1 == c3);
System.out.println("--------");
//Use the static method forName(String className) in Class
Class<?> c4 = Class.forName("com.itheima_02.Student");
System.out.println(c1 == c4);
}
}



public class Student {
    //Member variables: one private, one default, and one public
    private String name;
    int age;
    public String address;

    //Construction method: one private, one default and two public
    public Student() {
    }

    private Student(String name) {
        this.name = name;
    }

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

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

    //Member method: one private, four public
    private void function() {
        System.out.println("function");
    }

    public void method1() {
        System.out.println("method");
    }

    public void method2(String s) {
        System.out.println("method:" + s);
    }

    public String method3(String s, int i) {
        return s + "," + i;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                '}';
    }
}

result:


2.3 reflection acquisition construction method and use [application]
2.3.1Class class gets the method of constructing method objects

Method classification

Method nameexplain
Constructor<?>[] getConstructors()Returns the number of all public constructor objects
group
Constructor<?>[] getDeclaredConstructors()Returns an array of all constructor objects
Constructor getConstructor(Class<?>... parameterTypes)Returns a single common constructor object
Constructor getDeclaredConstructor(Class<?>...
parameterTypes)
Returns a single constructor object

Sample code
 

public class ReflectDemo01 {
public static void main(String[] args) throws ClassNotFoundException,
NoSuchMethodException, IllegalAccessException, InvocationTargetException,
InstantiationException {
//Get Class object
Class<?> c = Class.forName("com.itheima_02.Student");
//Constructor<?> [] getconstructors() returns an array containing constructor objects,
Constructor Object reflects the Class Object represents all public constructors of the class
// Constructor<?>[] cons = c.getConstructors();
//Constructor<?> [] getdeclaraedconstructors() returns the Class represented by the Class object
 Of all constructors declared Constructor Array of objects
Constructor<?>[] cons = c.getDeclaredConstructors();
for(Constructor con : cons) {
System.out.println(con);
} S
ystem.out.println("--------");
//Constructor < T > getconstructor (class <? >... Parametertypes) returns a
Constructor Object that reflects the Class Object represents the specified public constructor of the class
//Constructor < T > getdeclaraedconstructor (class <? >... Parametertypes) Returns
 One Constructor Object that reflects this Class The specified constructor of the class or interface represented by the object
//Parameters: the number of parameters of the constructor you want to obtain and the bytecode file object corresponding to the data type
Constructor<?> con = c.getConstructor();
//Constructor provides information and access rights for a single constructor of a class
//T newInstance(Object... initargs) uses the Constructor represented by this Constructor object,
Creates and initializes a new instance of the declared class of the constructor using the specified initialization parameters
Object obj = con.newInstance();
System.out.println(obj);
// Student s = new Student();
// System.out.println(s);
}
}


public class Student {
    //Member variables: one private, one default, and one public
    private String name;
    int age;
    public String address;

    //Construction method: one private, one default and two public
    public Student() {
    }

    private Student(String name) {
        this.name = name;
    }

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

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

    //Member method: one private, four public
    private void function() {
        System.out.println("function");
    }

    public void method1() {
        System.out.println("method");
    }

    public void method2(String s) {
        System.out.println("method:" + s);
    }

    public String method3(String s, int i) {
        return s + "," + i;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                '}';
    }
}

result:

Constructor<?>[] getConstructors()

Constructor<?>[] getDeclaredConstructors()

  2.3.2Constructor class method for creating objects

Method nameexplain
T newInstance(Object...initargs)Creates an object according to the specified construction method

2.4 get the construction method of reflection and use exercise 1 [application]
Case requirements
         Get common construction methods and create objects through reflection
code implementation
         Student class

package com.itheima_02;

public class Student {
    //Member variables: one private, one default, and one public
    private String name;
    int age;
    public String address;

    //Construction method: one private, one default and two public
       public Student() {
    }

    private Student(String name) {
        this.name = name;
    }

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

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

    //Member method: one private, four public
    private void function() {
        System.out.println("function");
    }

    public void method1() {
        System.out.println("method");
    }

    public void method2(String s) {
        System.out.println("method:" + s);
    }

    public String method3(String s, int i) {
        return s + "," + i;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", address='" + address + '\'' +
                '}';
    }
}



package com.itheima_03;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/*
    The following operations are realized through reflection:
        Student s = new Student("Lin Qingxia, "30," Xi'an ");
        System.out.println(s);
 */
public class ReflectDemo02 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //Get Class object
        Class<?> c = Class.forName("com.itheima_02.Student");

        //public Student(String name, int age, String address)
        //Constructor<T> getConstructor​(Class<?>... parameterTypes)
        Constructor<?> con = c.getConstructor(String.class, int.class, String.class);
        //The basic data type can also get the corresponding class type through. Class

        //T newInstance​(Object... initargs)
        Object obj = con.newInstance("Lin Qingxia", 30, "Xi'an");
        System.out.println(obj);
    }
}

 

  2.5 reflection acquisition construction method and use exercise 2 [application]
Case requirements
         Get private constructor and create object through reflection
code implementation
         Student class: see student class above
         Test class

public class ReflectDemo03 {
public static void main(String[] args) throws ClassNotFoundException,
NoSuchMethodException, IllegalAccessException, InvocationTargetException,
InstantiationException {
//Get Class object
Class<?> c = Class.forName("com.itheima_02.Student");
//private Student(String name)
//Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes)
Constructor<?> con = c.getDeclaredConstructor(String.class);
//Violent reflex
//public void setAccessible(boolean flag): if the value is true, the access check is canceled
con.setAccessible(true);
Object obj = con.newInstance("Lin Qingxia");
System.out.println(obj);
}
}

You cannot create an object through a private variable. Use setAccessible(true) to suppress access checking

  2.6 get member variables by reflection and use [application]
         2.6.1Class class method for obtaining member variable object
         Method classification

Method nameexplain
Field[] getFields()Returns an array of all public member variable objects
Field[] getDeclaredFields()Returns an array of all member variable objects
Field getField(String name)Returns a single public member variable object
Field getDeclaredField(String name)Returns a single member variable object
package com.itheima_04;

import com.itheima_02.Student;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/*
    Get member variables and use reflection
 */
public class ReflectDemo01 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //Get Class object
        Class<?> c = Class.forName("com.itheima_02.Student");

        //Field[] getFields() returns an array containing field objects that reflect all accessible public fields of the Class or interface represented by the Class object
        //Field [] getdeclaraedfields() returns an array of field objects, reflecting all fields declared by the Class or interface represented by the Class object
//        Field[] fields = c.getFields();
        Field[] fields = c.getDeclaredFields();
        for(Field field : fields) {
            System.out.println(field);
        }
        System.out.println("--------");

        //Field getField (String name) returns a field object that reflects the specified public member field of the Class or interface represented by the Class object
        //Field getdeclaraedfield (String name) returns a field object that reflects the specified declaration field of the Class or interface represented by the Class object
        Field addressField = c.getField("address");

        //Gets the object created by the parameterless constructor
        Constructor<?> con = c.getConstructor();
        Object obj = con.newInstance();

//        obj.addressField = "Xi'an";

        //Field provides information and dynamic access about a single field of a class or interface
        //void set (Object obj, Object value) sets the Field represented by this Field object in the specified object parameter to the specified new value
        addressField.set(obj,"Xi'an"); //Assign addressField to obj's member variable

        System.out.println(obj);



//        Student s = new Student();
//        s.address = "Xi'an";
//        System.out.println(s);
    }
}

result

  2.6.2Field class is used to assign values to member variables

Method nameexplain
voidset(Object obj,Object value)Assign value to the member variable of obj object

2.7 getting member variables by reflection and using exercise [application]
         Case requirements
                 Get and assign member variables through reflection
         code implementation
                Student class: see student class above
                 Test class

package com.itheima_04;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/*
    Exercise: do the following through reflection
        Student s = new Student();
        s.name = "Lin Qingxia ";
        s.age = 30;
        s.address = "Xi'an ";
        System.out.println(s);
 */
public class ReflectDemo02 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        //Get Class object
        Class<?> c = Class.forName("com.itheima_02.Student");

        //Student s = new Student();
        Constructor<?> con = c.getConstructor();
        Object obj = con.newInstance();
        System.out.println(obj);

        //s.name = "Lin Qingxia";
//        Field nameField = c.getField("name"); //NoSuchFieldException: name
        Field nameField = c.getDeclaredField("name");
        nameField.setAccessible(true);
        nameField.set(obj, "Lin Qingxia");
        System.out.println(obj);

        //s.age = 30;
        Field ageField = c.getDeclaredField("age");
        ageField.setAccessible(true);
        ageField.set(obj,30);
        System.out.println(obj);

        //s.address = "Xi'an";
        Field addressField = c.getDeclaredField("address");
        addressField.setAccessible(true);
        addressField.set(obj,"Xi'an");
        System.out.println(obj);
    }
}

  2.8 reflection method to obtain members and use [application]
2.8.1 method for class class to obtain member method object

Method classification

Method nameexplain
Method[] getMethods()Returns an array of all public member method objects, package
Including inherited
Method[] getDeclaredMethods()Returns an array of all member method objects, excluding
Inherited
Method getMethod(String name, Class<?>...
parameterTypes)
Returns a single public member method object
Method getDeclaredMethod(String name, Class<?>...
parameterTypes)
Returns a single member method object

Sample code
 

package com.itheima_05;

import com.itheima_02.Student;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/*
    Get member methods and use reflection
 */
public class ReflectDemo01 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //Get Class object
        Class<?> c = Class.forName("com.itheima_02.Student");

        //Method[] getMethods() returns an array containing method objects that reflect all public methods of the Class or interface represented by the Class object, including objects declared by the Class or interface and classes inherited from superclasses and superinterfaces
        //Method[] getDeclaredMethods() returns an array containing method objects that reflect all declared methods of the Class or interface represented by the Class object, including public, protected, default (package) access and private methods, but excluding inherited methods
//        Method[] methods = c.getMethods();
        Method[] methods = c.getDeclaredMethods();
        for(Method method : methods) {
            System.out.println(method);
        }
        System.out.println("--------");

        //Method getMethod (string name, Class <? >... Parametertypes) returns a method object that reflects the specified public member methods of the Class or interface represented by the Class object
        //Method getdeclaraedmethod (string name, Class <? >... Parametertypes) returns a method object that reflects the specified declared method Class object of the represented Class or interface
        //public void method1()
        Method m = c.getMethod("method1");

        //Gets the object created by the parameterless constructor
        Constructor<?> con = c.getConstructor();
        Object obj = con.newInstance();

//        obj.m();

        //Provides information and access to a single method on a class or interface
        //Object invoke (Object obj, Object... args) calls the base method represented by this method object on the specified object with the specified parameters
        //Object: return value type
        //obj: the object that calls the method
        //args: parameter required by method
        m.invoke(obj);

//        Student s = new Student();
//        s.method1();
    }
}

  2.8.2Method class is used to execute the method

Method nameexplain
Object.invoke(Object obj,Object... args)Call the obj Object, call the member method of the Object object, the parameter is args, and the return value is Object type

2.9 reflection acquisition method and use practice [application]
Case requirements
         Get member methods through reflection and call
code implementation
         Student class: see student class above
         Test class

package com.itheima_05;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/*
     Exercise: do the following through reflection
        Student s = new Student();
        s.method1();
        s.method2("Lin Qingxia ");
        String ss = s.method3("Lin Qingxia ", 30);
        System.out.println(ss);
        s.function();
 */
public class ReflectDemo02 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //Get Class object
        Class<?> c = Class.forName("com.itheima_02.Student");

        //Student s = new Student();
        Constructor<?> con = c.getConstructor();
        Object obj = con.newInstance();

        //s.method1();
        Method m1 = c.getMethod("method1");
        m1.invoke(obj);

        //s.method2("Lin Qingxia");
        Method m2 = c.getMethod("method2", String.class);
        m2.invoke(obj,"Lin Qingxia");

//        String ss = s.method3("Lin Qingxia", 30);
//        System.out.println(ss);
        Method m3 = c.getMethod("method3", String.class, int.class);
        Object o = m3.invoke(obj, "Lin Qingxia", 30);
        System.out.println(o);

        //s.function();
//        Method m4 = c.getMethod("function"); //NoSuchMethodException: com.itheima_02.Student.function()
        Method m4 = c.getDeclaredMethod("function");
        m4.setAccessible(true);
        m4.invoke(obj);
    }
}

  2.10 cases of reflection [application]
2.10.1 generic checking of reflection exercises
Case requirements
Through reflection technology, add some string data to a collection whose generic type is Integer
code implementation

package com.itheima_06;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

/*
    Exercise 1: I have an ArrayList < integer > set. Now I want to add a string data to this set. How to implement it?
 */
public class ReflectTest01 {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        //Create collection
        ArrayList<Integer> array = new ArrayList<Integer>();

//        array.add(10);
//        array.add(20);
//        array.add("hello");

        Class<? extends ArrayList> c = array.getClass();
        Method m = c.getMethod("add", Object.class);

        m.invoke(array,"hello");
        m.invoke(array,"world");
        m.invoke(array,"java");

        System.out.println(array);
    }
}

2.10.2 specified method of specified class in operation configuration file
Case requirements
Run the specified method of the specified class in the configuration file through reflection
code implementation
 

package com.itheima_06;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;

/*
    Exercise 2: running methods in a class through a configuration file
 */
public class ReflectTest02 {
    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
//        Student s = new Student();
//        s.study();

//        Teacher t = new Teacher();
//        t.teach();

        /*
            class.txt
            className=xxx
            methodName=xxx
         */

        //Load data
        Properties prop = new Properties();
        FileReader fr = new FileReader("myReflect\\class.txt");
        prop.load(fr);
        fr.close();

        /*
            className=com.itheima_06.Student
            methodName=study
         */
        String className = prop.getProperty("className");
        String methodName = prop.getProperty("methodName");

        //Use by reflection
        Class<?> c = Class.forName(className);//com.itheima_06.Student

        Constructor<?> con = c.getConstructor();
        Object obj = con.newInstance();

        Method m = c.getMethod(methodName);//study
        m.invoke(obj);
    }
}

 

Tags: Java Back-end

Posted on Mon, 08 Nov 2021 16:24:01 -0500 by shameermp