Loader like JAVA & Reflection & modularization

1. Class loader

Class 1.1 loading

1.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 nothing unexpected happens, JVM These three steps will be completed continuously, so sometimes these three steps are collectively referred to as class loading or class initialization
2.Class loading
	It means to class Read the file into memory and create a java.lang.Class object
	When any class is used, the system will create a java.lang.Class object
3.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
4.Class initialization
	In this stage, class variables are mainly initialized
5.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 step 1 for the direct parent class-3
6.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 a corresponding class or interface java.lang.Class object
	Initializes a subclass of a class
	Direct use java.exe Command to run a main class

Class 1.2 loader

1.Role of class loader:
	Be responsible for.class Load the file into memory and generate the corresponding java.lang.Class Object. 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!
2.JVM Class loading mechanism
	Overall responsibility:
		When a class loader is responsible for loading a Class When, the Class Other dependent and referenced Class This class loader will also be responsible for loading, unless it is shown that another class loader is used for loading
	Parent delegate:
		When a class loader is responsible for loading a Class First, let the parent loader try to load the Class,Try to load the class from your own classpath only if the parent classloader cannot load the class
	Caching mechanism:
		Ensure that all loaded Class Will be cached when the program needs to use a Class Object, the classloader first searches the cache for the object Class,Only if the does not exist in the cache Class Object, the system will read the binary data corresponding to this class and convert it into Class Object, stored in cache
3.Java Built in class loader in:
	Bootstrap class loader
		It is the built-in class loader of the virtual machine, usually expressed as null ,And no father null
	Platform class loader
		The platform class loader can see all platform classes, including those defined by the platform class loader or its ancestors Java SE platform API,Its implementation class and JDK Specific runtime classes
	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 JDK Classes on specific tools
	Inheritance relationship of class loader
		System The parent loader of is Platform,and Platform The parent loader of is Bootstrap
ClassLoader Two methods in
	static ClassLoader getSystemClassLoader()
		Returns the system class loader used for delegation
	ClassLoader getParent()
		Returns the parent loader for delegation

2. Reflection

2.1 general

   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 objects

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

  code implementation:

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.2 obtaining construction method

   Class gets the method of constructing method object:

  code implementation:

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

   methods used by Constructor class to create objects:

2.3 getting member variables

Method for Class to get member variable object:

  code implementation:

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

   Field class is used to assign values to member variables:

2.4 method of obtaining members

Class gets the method of the member object:

  code implementation:

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

  Method class is used to execute the Method:

2.5 cases

Generic checking of reflection exercises
	Case requirements  : Through reflection technology, to a generic Integer Add some string data to the collection

  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);
    }
}
Run the specified method of the specified class in the 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 general

	a.Java With the development of these years, language has become a far-reaching programming language, which is adopted by countless platforms and systems Java Language. But with development, Java It 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 be used Java Some of the core functions of, JVM Also load the entire JRE environment
	b.To give Java""Slimming down", let Java Lightweight, Java 9 The modular system was officially launched. Java Split into N Multiple modules and allow Java The program can select the necessary to load the program as needed Java Module so that Java Run in a lightweight manner
	c.Actually, Java 7 The concept of modularity has been put forward, but because it is too complex, Java 7,Java 8 Has been unable to really launch until Java 9 To really mature. about Java In terms of language, modular system is a real self innovation, which makes the "old and huge" system Java Language is rejuvenated with young vitality

Basic use of module services

  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.2 basic use of module services

  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

4. Reflect common interview questions

1. What is reflection?
   reflection is that you can know all the properties and methods of any class in the running state; For any object, you can call any of its methods and properties; This kind of dynamically obtained information and the function of dynamically calling object methods are called the reflection mechanism of Java language.

2. Where is the reflection mechanism used?
   in a.JDBC, the database driver is dynamically loaded by reflection.
  the service method of Sevlet is called by reflection in b.Web server.
  c.Eclispe and other development tools use reflection to dynamically analyze the type and structure of objects and dynamically prompt the attributes and methods of objects.
  d. many frameworks use reflection mechanism, inject attributes and call methods, such as Spring.

3. Advantages and disadvantages of reflection mechanism?
   advantages: it can be executed dynamically. During operation, it can dynamically execute methods and access attributes according to business functions, giving full play to the flexibility of java.
  disadvantages: it has an impact on performance. Such operations are always slower than direct execution of java code

4. The role of java reflection mechanism
   a. judge the class of any object at run time
   b. construct the object of any class at run time
   c. judge the member variables and methods of any class at run time
   d. call the method of any object at run time

5. How to use Java reflection?
   A. create an object with a fully qualified class name
     1.) Class.forName("full class name"); For example, the com.mysql.jdbc.Driver Driver class has been loaded into the jvm and the initialization of the class has been completed
     2.) class name. Class; Get class <? > CLZ object
     3.) object. getClass();
   b. get the constructor object and get an object through the constructor new
    1.) Clazz.getConstructor([String.class]);
     2.) Con.newInstance([parameter]);
   c. create an instance object through the class object (equivalent to the new class name () parameterless constructor)
    1.) Cls.newInstance();
   d. obtain an attribute object through the class object
     1.) Field c=cls.getFields(): get all the public fields of a class, including the fields in the parent class.
     2.) field C = CLS. Getdeclaraedfields(): obtain all declared fields of a class, that is, including public, private and protected, but excluding the declared fields of the parent class
  e. obtain a method object through the class object
     1.) Cls.getMethod("method name", class... parameaType); (only public can be obtained)
     2.) Cls.getDeclareMethod("method name"); (obtain any modified method, and cannot execute private)
     3.) M.setAccessible(true); (make private methods executable)
  f. let the method execute
     1.) Method.invoke(obj instance object, obj variable parameter); ------ (with return value)

Tags: Java reflection

Posted on Sun, 19 Sep 2021 15:58:48 -0400 by riddhi