Class Loader-Reflection-Modularization

Keywords: Java jvm JDK Attribute

1. Class loader

Class 1.1 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 surprises, the JVM will continue to complete these three steps, so sometimes these three steps are collectively referred to as class loading or class initialization.
  • Class loading
    • That is to read the class file into memory and create a java.lang.Class object for it.
    • When any class is used, the system creates a java.lang.Class object for it.
  • Connection of classes
    • Verification phase: Used to verify that the loaded class has the correct internal structure and is in harmony with other classes
    • Preparatory phase: Responsible for allocating memory for class variables of the class and setting default initialization values
    • Parsing phase: Replace symbolic references in class binary data with direct references
  • Class initialization
    • At this stage, the main task is to initialize class variables.
  • Class initialization steps
    • If the class has not been loaded and connected, the program first loads and connects the class
    • If the direct parent of the class has not been initialized, the direct parent of the class is initialized first.
    • If there are initialization statements in the class, the system executes these initialization statements in turn
    • Note: When the second step is executed, the initialization step of the direct parent class is also followed by the initialization step 1-3.
  • Class initialization timing
    • Create instances of classes
    • Calling class methods of classes
    • Accessing or assigning class variables to a class or interface
    • Mandatory creation of java.lang.Class objects corresponding to a class or interface using reflection
    • Initialize subclasses of a class
    • Running a main class directly using the java.exe command

Class 1.2 Loader [Understanding]

Function of Class 1.2.1 Loader

  • It is responsible for loading. class files into memory and generating corresponding java.lang.Class objects for them. 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!

Class Loading Mechanism of 1.2.2 JVM

  • Full responsibility: When a class loader is responsible for loading a Class, the other classes that the Class depends on and references will also be loaded by the class loader, unless it shows that another class loader is used for loading.
  • Parent Delegation: When a class loader is responsible for loading a Class, it first lets the parent loader try to load the Class. Only when the parent loader cannot load the class, it tries to load the class from its own class path.
  • Caching mechanism: ensure that all loaded Classes will be cached. When a 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 corresponding binary data of the class and convert it into Class object, which will be stored slowly. Deposit area

Built-in class loader in 1.2.3 Java

  • Bootstrap class loader: It is a built-in class loader for virtual machines, usually expressed as null, and has no parent null
  • Platform class loader: The platform class loader can see all the platform classes, including the Java SE platform API defined by the platform class loader or its ancestors, its implementation classes and JDK-specific runtime classes.
  • System class loader: It is also called application class loader, unlike platform class loader. System class loaders are commonly used to define application class paths, module paths, and classes on JDK-specific tools
  • Inheritance relationship of class loaders: System's parent loader is Platform, while Platform's parent loader is Bootstrap

Two Methods in 1.2.4 ClassLoader

  • Method Classification

    Method name Explain
    static ClassLoader getSystemClassLoader() Returns the system class loader for delegation
    ClassLoader getParent() Return to the parent loader for delegation
  • Sample code

    public class ClassLoaderDemo {
        public static void main(String[] args) {
            //static ClassLoader getSystemClassLoader(): Returns the system class loader for delegation
            ClassLoader c = ClassLoader.getSystemClassLoader();
            System.out.println(c); //AppClassLoader
    
            //ClassLoader getParent(): Returns the parent 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 getting the variables and method information of a class at run time. Then it creates objects and invokes a mechanism of methods by obtaining information. Because of this dynamic nature, it can greatly enhance the flexibility of the program. The program does not need to complete the determination at compile time, but can still be extended at run time.

2.2 Three Ways of Obtaining Class Class Objects [Application]

2.2.1 Three types of classification

  • Class name. class attribute
  • Object name. getClass() method
  • Class. forName (full class name) method

2.2.2 sample code

public class ReflectDemo {
    public static void main(String[] args) throws ClassNotFoundException {
        //Use the class attribute of the class to get the corresponding Class object of 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 and 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 the Class class
        Class<?> c4 = Class.forName("com.itheima_02.Student");
        System.out.println(c1 == c4);
    }
}

2.3 Construction method of reflection acquisition and its application

2.3.1 Class class acquisition method for constructing method objects

  • Method Classification

    Method name Explain
    Constructor<?>[] getConstructors() Returns an array of all common 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 the Class object
            Class<?> c = Class.forName("com.itheima_02.Student");
    
            //Constructor<?>[] getConstructors () returns an array containing Constructor objects, which reflect all the common constructors of the class represented by the Class object.
    //        Constructor<?>[] cons = c.getConstructors();
            //Constructor<?>[] getDeclared Constructors () 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 > getDeclared Constructor (Class <?> parameterTypes) returns a Constructor object that reflects the specified constructor of the class or interface represented by the Class object.
            //PARAMETER: The number of parameters you want to obtain for the constructor 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 the Constructor object and uses the specified initialization parameters to create and initialize new instances of the declared class of the constructor
            Object obj = con.newInstance();
            System.out.println(obj);
    
    //        Student s = new Student();
    //        System.out.println(s);
        }
    }
    

2.3.2 Constructor Class Method for Creating Objects

Method name Explain
T newInstance(Object...initargs) Create objects according to the specified constructor

2.4 Reflection acquisition construction method and use Exercise 1 [Application]

  • Case requirements

    • Getting common constructs and creating objects through reflection
  • code implementation

    • Student category

      public class Student {
          //Membership variables: a private, a default, and a public
          private String name;
          int age;
          public String address;
      
          //Constructor: one private, one default, 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;
          }
      
          //Membership 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 the 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);
              //Basic data types can also be obtained by. 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 exercise 2 [Application]

  • Case requirements

    • Getting private constructors and creating objects 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 the 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): Value true, cancel access check
              con.setAccessible(true);
      
              Object obj = con.newInstance("Lin Qingxia");
              System.out.println(obj);
          }
      }
      

2.6 Reflection to obtain member variables and use [application]

2.6.1 Class Class Class Method for Obtaining Membership Variable Objects

  • Method Classification

    Method name Explain
    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 the Class object
            Class<?> c = Class.forName("com.itheima_02.Student");
    
            //Field[] getFields() returns an array containing the Field object, which reflects all accessible public fields of the class or interface represented by the Class object.
            //Field[] getDeclaredFields() 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 common member fields of the class or interface represented by the Class object.
            //Field getDeclaredField(String name) returns a Field object that reflects the specified declaration fields of the class or interface represented by the Class object.
            Field addressField = c.getField("address");
    
            //Get a parametric-free constructor to create an object
            Constructor<?> con = c.getConstructor();
            Object obj = con.newInstance();
    
    //        obj.addressField = Xi'an;
    
            //Field provides information and dynamic access to individual fields 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"); //Appoint the member variable addressField of obj to Xi'an
    
            System.out.println(obj);
    
    
    
    //        Student s = new Student();
    //        s.address = Xi'an;
    //        System.out.println(s);
        }
    }
    

2.6.2Field Class Method for Assigning Membership Variables

Method name Explain
voidset(Object obj,Object value) Assign value to member variables of obj objects

2.7 Reflection to obtain member variables and use exercises [application]

  • Case requirements

    • Obtain member variables by reflection and assign values
  • code implementation

    • Student Class: See Student Class above.

    • Test class

      public class ReflectDemo02 {
          public static void main(String[] args) throws Exception {
              //Get the 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 Reflective member acquisition method and use [application]

2.8.1 Class Class Class Method for Obtaining Membership Method Objects

  • Method Classification

    Method name Explain
    Method[] getMethods() Returns an array of all public member method objects, including inherited ones
    Method[] getDeclaredMethods() Returns an array of all member method objects, excluding inherited ones
    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 the Class object
            Class<?> c = Class.forName("com.itheima_02.Student");
    
            //Method[] getMethods() returns an array containing method objects that reflect all common methods of classes or interfaces represented by the Class object, including objects declared by classes or interfaces, and classes inherited from superclasses and superinterfaces.
            //Method[] getDeclaredMethods() returns an array containing method objects that reflect all declarative methods of classes or interfaces represented by Class objects, including public, protected, default (package) access and private methods, but excluding inheritance 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 method of the class or interface represented by the Class object.
            //Method getDeclared Method (String name, Class <?>... parameterTypes) returns a method object that reflects the specified declared method Class object of the class or interface represented by it.
            //public void method1()
            Method m = c.getMethod("method1");
    
            //Get a parametric-free constructor to create an object
            Constructor<?> con = c.getConstructor();
            Object obj = con.newInstance();
    
    //        obj.m();
    
            //Providing information about a single method and access rights on a class or interface
            //Object invoke(Object obj, Object... args) invokes the underlying method of object representation on specified objects with specified parameters
            //Object: Return value type
            //obj: Object that calls a method
            //args: the parameters required by the method
            m.invoke(obj);
    
    //        Student s = new Student();
    //        s.method1();
        }
    }
    

2.8.2 Method Class for Method Execution

Method name Explain
Objectinvoke(Object obj,Object... args) Call the member method of the obj object, the parameter is args, and the return value is Object type

2.9 Reflective Membership Method and Exercise [Application]

  • Case requirements

    • Retrieve member methods by reflection and call them
  • code implementation

    • Student Class: See Student Class above.

    • Test class

      public class ReflectDemo02 {
          public static void main(String[] args) throws Exception {
              //Get the 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. method 2 ("Lin Qingxia");
              Method m2 = c.getMethod("method2", String.class);
              m2.invoke(obj,"Lin Qingxia");
      
      //        String s s = 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 Reflection Case [Application]

2.10.1 Override Generic Examination for Reflection Exercises

  • Case requirements

    • Adding string data to a collection of generic Integer s by reflection technology
  • code implementation

    public class ReflectTest01 {
        public static void main(String[] args) throws Exception {
            //Create collections
            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 Running Configuration File Specifies Classes

  • Case requirements

    • Running the specified method of the class in the configuration file by reflection
  • code implementation

    public class ReflectTest02 {
        public static void main(String[] args) throws Exception {
            //Loading 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. Numerous platforms and systems are written in Java language. However, with the development of Java, it has become more and more huge, and gradually developed into a "bloated" language. Moreover, whether it is running a large software system or a small program, even if the program only needs to use some of the core functions of Java, the JVM has to load the entire JRE environment.
In order to "slim down" Java and make it lightweight, Java 9 formally introduced modular system. Java is split into N modules and allows Java programs to select the Java modules necessary for the loader as needed so that Java can run in a lightweight manner.

In fact, the concept of modularity was put forward in Java 7, but because of its complexity, Java 7 and Java 8 were not really launched until Java 9 really matured. For the Java language, modular systems are a real self-innovation that revitalizes the "old and huge" Java language.

Basic Use of 3.2 Module [Application]

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

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

    [External Link Picture Transfer Failure (img-nwKtr9wd-1565867395124) (img 01.png)]

    [External Link Picture Transfer Failure (img-kQD3YXqs-1565867395127) (img 02.png)]

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

    [External Link Picture Transfer Failure (img-qycsSm4o-1565867395127) (img 03.png)]

    [External Link Picture Transfer Failure (img-PxuPgEoX-1565867395128) (img04.png)]

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

    [External Link Picture Transfer Failure (img-viF79DAa-1565867395128) (img05.png)]

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

    [External Link Picture Transfer Failure (img-JL6402RS-1565867395129) (img png)]

3.3 Basic Use of Modular Services [Applications]

  1. Create a new package in myOne module to provide an interface and two implementation classes

    [External Link Picture Transfer Failure (img-AbcNG65U-1565867395129) (img07.png)]

    [External Link Picture Transfer Failure (img-WKwC2a3l-1565867395130) (img png)]

    [External Link Picture Transfer Failure (img-nMAy31tc-1565867395130) (img png)]

  2. Modify the module-info.java file in the myOne module to add the following

    [External Link Picture Transfer Failure (img-Exjnjhuq-1565867395130) (img 10.png)]

  3. Create a new test class in myTwo module

    [External Link Picture Transfer Failure (img-DjOdIPSk-1565867395130) (img11.png)]

    [External Link Picture Transfer Failure (img-E9w1k8ry-1565867395131) (img 12.png)]

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

    [External Link Picture Transfer Failure (img-Enw0AxZ8-1565867395131) (img 13.png)]

-viF79DAa-1565867395128)]

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

    [External Chain Picture Transfer.. (img-JL6402RS-1565867395129)]

3.3 Basic Use of Modular Services [Applications]

  1. Create a new package in myOne module to provide an interface and two implementation classes

    [External Chain Picture Transfer.. (img-AbcNG65U-1565867395129)]

    [External Chain Picture Transfer.. (img-WKwC2a3l-1565867395130)]

    [External Chain Picture Transfer.. (img-nMAy31tc-1565867395130)]

  2. Modify the module-info.java file in the myOne module to add the following

    [External Chain Picture Transfer.. (img-Exjnjhuq-1565867395130)]

  3. Create a new test class in myTwo module

    [External Chain Picture Transfer.. (img-DjOdIPSk-1565867395130)]

    [External Chain Picture Transfer.. (img-E9w1k8ry-1565867395131)]

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

    [External Chain Picture Transfer.. (img-Enw0AxZ8-1565867395131)]

Posted by smilesmita on Thu, 15 Aug 2019 04:27:54 -0700