Reflection get Class create object call method

Overview of reflection

  1. Reflection is the key to being regarded as a dynamic language. Reflection mechanism allows programs to obtain the internal information of any class with the help of Reflection API during execution, and can directly operate the internal properties and methods of any object.
    Frame = reflection + annotation + design pattern.
  2. Functions provided by reflection mechanism:

Class class understanding and obtaining class class instances

Class understanding

  1. Class loading process: the program passes javac Exe command will generate one or more bytecode files (. End of class). Then we use Java Exe command to interpret and run a bytecode file. It is equivalent to loading a bytecode file into memory. This process is called class loading. The class loaded into memory is called the runtime class. This runtime class is used as an instance of class.
  2. In other words, an instance of Class corresponds to a runtime Class.
  3. Runtime classes loaded into memory will be cached for a certain period of time. Within this time, we can do it in different ways
    To get this runtime class.

Four methods to get Class instances

public class GetClass {
	public static void main(String[] args) throws ClassNotFoundException {
		//Method 1: call the properties of the runtime class: Class (disadvantage: write dead)
		Class c1 = Person.class;
		System.out.println(c1);  //class com.xd.Person is class plus fully qualified class name
		
		//Method 2: call the runtime class object and call getClass()
		Person p = new Person();
		Class c2 = p.getClass();
		System.out.println(c2);
		
		//Method 3: call the static method of Class: froName(String classPath) (multiple used)
		Class c3 = Class.forName("Test.Person");
		System.out.println(c3);
		
		//Method 4: use ClassLoader
		ClassLoader classLoader = GetClass.class.getClassLoader();
		Class c4 = classLoader.loadClass("Test.Person");
		System.out.println(c4);
		
		System.out.println(c1==c2); //true
		System.out.println(c1==c3);  //true
	}
}

ClassLoader class

Class loader function

  1. Load the bytecode content of the class file into memory, convert the static data into the run-time data structure of the method area, and then generate a Java. Net file representing this class in the heap Lang. class object, as the access entry of class data in the method area.
  2. Class caching: the standard JavaSE class loader can find classes as required, but once a class is loaded into the class loader, it will remain loaded (cached) for a period of time. However, the JVM garbage collection mechanism can recycle these class objects.

Loading configuration files using Classloader

public class ClassLoaderProperty {	
	public static void main(String[] args) throws IOException {		
	
		Properties pros = new Properties();
		
		InputStream in = ClassLoaderProperty.class.getClassLoader().getResourceAsStream("jdbc.properties");
		pros.load(in);	
		System.out.println(pros.getProperty("name"));  //Xiong Da
	}
}

Configuration file JDBC properties

name = Xiong Da

Create a runtime class object

Class clazz = Person.class;
//newInstance(): call this method to create the object of the corresponding runtime class. Constructor that internally calls an empty parameter of the runtime class.
Person p= (Person)clazz.newInstance();

Call the specified constructor:

@Test
public void testConstructor() throws Exception {
    Class clazz = Person.class;
    //private Person(String name)
   // 1. Get the specified constructor getdeclaraedconstructor(): parameter: indicates the parameter list of the constructor
   
    Constructor constructor = clazz.getDeclaredConstructor(String.class);

    //2. Ensure that the constructor is accessible and the constructor has public permission. Skip this step
    constructor.setAccessible(true);

    //3. Call this constructor to create the object of the runtime class
    Person per = (Person) constructor.newInstance("Tom");
}

Call the specified property

    //1. Getdeclaraedfield (string fieldname): get the attribute of the specified variable name in the runtime class
    Field name = clazz.getDeclaredField("name");

    //2. Ensure that the current attribute is accessible
    name.setAccessible(true);
    //3. Get and set the property value of the specified object
    name.set(p,"Tom");

    System.out.println(name.get(p));
}

Call the specified method

         //1. Get a specified method
         //getDeclaredMethod(): parameter 1: indicates the name of the obtained method. Parameter 2: indicates the formal parameter list of the obtained method. Empty parameters are not written
        Method show = clazz.getDeclaredMethod("show", String.class);
        
        //2. Ensure that the current method is accessible. If the public permission is skipped
        show.setAccessible(true);

         //3. invoke() of calling method: parameter 1: caller of method; parameter 2: argument assigned to method parameter
         //The return value of invoke() is the return value of the method called in the corresponding class.
        Object returnValue = show.invoke(p,"CHN"); 
        System.out.println(returnValue);

        System.out.println("*************How to call static methods*****************");

        // private static void showDesc()

        Method showDesc = clazz.getDeclaredMethod("showDesc");
        showDesc.setAccessible(true);
        //This invoke() returns null if the method in the called runtime class does not return a value
//        Object returnVal = showDesc.invoke(null);
        Object returnVal = showDesc.invoke(Person.class);
        System.out.println(returnVal);//null

Added by Jaguar83 on Mon, 27 Dec 2021 15:17:44 +0200