day24 class loader & Reflection & modularization

Keywords: Java java web

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 initialize the class through three steps: class loading, class connection and class initialization. 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 need to care too much about the class loading mechanism, we can better understand the operation of the program by understanding this mechanism!

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 loader, unless it is shown that another Class loader is used for loading
  • Parent Class delegation: when a Class loader is responsible for loading a Class, first let the parent Class loader try to load the Class, and only try to load the Class from its own Class path when the parent Class loader cannot load the Class
  • Caching mechanism: ensure that all loaded classes will be cached. When the program needs to use a Class object, the Class loader first searches the Class from the cache. Only when the Class object does not exist in the cache, the system will read the binary data corresponding to the Class, convert it into a Class object and store it in the 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 SE platform API defined by the platform class loader or its ancestors, 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 classloader is usually used to define application 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
        }
    }
    

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);
    }
}

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 an array of all public constructor objects
    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 the constructor object, which reflects all public constructors of the Class represented by the Class object
    //        Constructor<?>[] cons = c.getConstructors();
            //Constructor<?> [] getdeclaredconstructors() returns an array of constructor objects that reflect all constructors declared by the Class represented by the Class object
            Constructor<?>[] cons = c.getDeclaredConstructors();
            for(Constructor con : cons) {
                System.out.println(con);
            }
            System.out.println("--------");
    
            //Constructor < T > getconstructor (Class <? >... Parametertypes) returns a constructor object that reflects the specified public constructor of the Class represented by the Class object
            //Constructor < T > getdeclaraedconstructor (Class <? >... Parametertypes) returns a constructor object that reflects the specified constructor of the Class or interface represented by this Class 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 and uses the specified initialization parameters to create and initialize a new instance of the declaration class of the Constructor
            Object obj = con.newInstance();
            System.out.println(obj);
    
    //        Student s = new Student();
    //        System.out.println(s);
        }
    }
    

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

      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 + '\'' +
                      '}';
          }
      }
      
    • Test class

      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);
          }
      }
      

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
  • Sample code

    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);
        }
    }
    

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

      public class ReflectDemo02 {
          public static void main(String[] args) throws Exception {
              //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, 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

    public class ReflectDemo01 {
        public static void main(String[] args) throws Exception {
            //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
Objectinvoke(Object obj,Object... args)Call the member method of obj 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

      public class ReflectDemo02 {
          public static void main(String[] args) throws Exception {
              //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

    public class ReflectTest01 {
        public static void main(String[] args) throws Exception {
            //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

    public class ReflectTest02 {
        public static void main(String[] args) throws Exception {
            //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);
        }
    }
    

3. Modularization

3.1 modular overview [understanding]

With the development of these years, Java language has become a far-reaching programming language. Countless platforms and systems are written in Java language. However, with the development of Java, Java has become more and more huge and gradually developed into a "bloated" language. Moreover, whether running a large software system or running a small program, even if the program only needs to use some core functions of Java, the JVM also needs to load the whole JRE environment.
In order to "downsize" Java and make Java lightweight, Java 9 officially launched a modular system. Java is divided into N modules and allows Java programs to select the Java modules necessary for loading programs as needed, so that Java can run in a lightweight manner

In fact, the concept of modularity has been put forward in Java 7, but because it is too complex, Java 7 and Java 8 have not been really launched until Java 9 is really mature. For the Java language, modular system is a real self innovation, which makes the "old and huge" Java language rejuvenated with young vitality

3.2 basic use of modules [ application ]

  1. Create two modules in the project. One is myOne and the other is myTwo

  2. Create the following packages and classes in the myOne module, and add methods to the classes

  3. Create the following packages and classes in the myTwo module, and create objects in the classes and use

  4. In the src directory of the myOne module, create module-info.java and write the following

  5. In the src directory of the myTwo module, create module-info.java and write the following

3.3 basic use of module services [ application ]

  1. Create a new package in the myOne module, providing an interface and two implementation classes


  2. Modify the module-info.java file in the myOne module and add the following
  3. Create a new test class in the myTwo module

  4. Modify the module-info.java file in the myTwo module and add the following

Posted by mikeissa on Sun, 19 Sep 2021 23:17:10 -0700