Java series notes 16 - Reflection

reflex

Class loader

When the 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 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
  • If any class is used, the system will create a Java Lang.class object

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 and set default initial values
  • 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 loading

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 the second step, 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. Net corresponding to a class or interface Lang.class object
  • Initializes a subclass of a class
  • Directly use Java Exe command to run a main class

Class loader

Role of class loader

  • Be responsible for The class file is loaded into memory and the corresponding Java. Java. Class file is generated for it Lang.class object
  • Although we don't have to worry too much about the class loading mechanism, we can better understand the operation of the program by understanding this mechanism

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

The class loader is the object responsible for loading classes

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ds9ou0am-1642473736582) (C: \ users \ ZY \ appdata \ roaming \ typora \ user images \ image-20210614141543216. PNG)]

Two methods in ClassLoader

  • static ClassLoader getSystemClassLoader()
    Returns the system class loader used for delegation
  • ClassLoader getParent(): returns the parent class loader for delegation

reflex

Java reflection mechanism: it refers to obtaining the variable and method information of a class at runtime. 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 expanded at the run time

Gets the object of Class

If we want to use a Class through reflection, first we need to get the bytecode file of the Class, that is, the object of type Class

Here, we provide three ways to obtain objects of Class type

  • Use the class attribute of the class to get the class object corresponding to the class

    It is mainly used for obtaining bytecode of objects

    Example: Student Class will return the class object corresponding to the Student class

  • Call the getClass() method of the object to return the Class object corresponding to the Class to which the object belongs

    It is used to transfer parameters

    This method is a method of the Object class. All Java objects can call this method

  • Use the static method forName(String className) in Class This method needs to pass in a string parameter whose value is the full path of a Class, that is, the path of the full package name

    It is mostly used for configuration files. It defines the class name in the configuration file, reads the file, and loads the class

Conclusion:
The same bytecode file (*. class) will only be loaded once during a program run, and the class object obtained by either method is the same

Reflection gets the construction method and uses it

The method used to get the constructor in Class

//Returns an array of all public constructor objects
Constructor<?>[] getConstructors();

//Returns an array of all constructor objects
Constructor<?>[] getDeclaredConstructors();

//Returns a single common constructor object
Constructor<T> getConstructor(Class<?>...parameterTypes);

//Returns a single constructor object
Constructor<T> getDeclaredConstructor(Class<?>...parameterTypes);

Methods used to create objects in the Constructor class

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

Example 1

public static void main(String[] args) throws ClassNotFoundException,NoSuchMethodException{
	//Get class object
	Class<?> c = Class.forName("com.lanh.Student");
	
	//public Student(String name,int age,String address)
	//Constructor<T> getConstructor(Class<?>...parameterTypes)
	Constructor<?> con = c.getConstructor(String.class,int.class,String.class);

	//T newInstance(Object...initargs)
	Object obj = con.newInstance("Xiao Ming",19,"Guangdong");
}

The basic data type can also be passed through Class gets the corresponding class type

Exercise 2:

public static void main(String[] args){
	//Get Class object
	Class<?> c = Class.forName("com.lanh.Student");

	//private Student(String name)
	//constructor<T> getDeclareConstructor(Class<?>...parameterTypes)
	Constructor<?> con = c.getDeclareConstructor(String.class);
	
	//Violent reflex
	//public void setAccessible(boolean flag): if the flag value is true, cancel the access check
	con.setAccessible(true);
	
	Object obj = con.newInstance("Xiaodong");
	System.out.println(obj);
}

public void setAccessible(boolean flag): if the value is true, the access check is canceled

Method used to get member variables in Class

//Returns an array of all public member variable objects
Field[] getFields();

//Returns an array of all member variable objects
Field[] getDeclaredFields();

//Returns a single public member variable object
Field getField(String name);

//Returns a single member variable object
Field getDeclaredField(String name);

The method in the Field class used to assign values to member variables

//Assign value to the member variable of obj object
void set(Object obj,Object value);

Get member methods and use reflection

The method used to get member methods in Class

//Returns all public member method objects, including inherited
Method[] getMethods();

//Returns all member method objects, excluding inherited
Method[] getDeclaredMethods();

//Returns a single public member method object
Method getMethod(String name,Class<?>...parameterTypes);

//Returns a single public member method object
Method getDeclaredMethod(String name,Class<?>...parameterTypes);

Method class is used to call member methods

//Call the member method of obj Object. The parameter is args and the return value is Object type
Object invoke(Object obj,Object...args);

Generic check of reflection exercise:

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

n.invoke(array,"hello");
n.invoke(array,"world");
System.out.println(array);
//Output results ["hello","world"]

What is specified in the run profile of the exercise

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

/*myReflect\\class.txt
className = "com.lanh.Stuent"
methodName = "study"
*/
className = prop.getProperty("className");
String methodName = prop.getProperty("methodMethod");

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

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

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

Keywords: Java Back-end

Added by fuzz01 on Tue, 18 Jan 2022 17:58:54 +0200