[Java SE] Reflection

I learned
reflection a long time ago. I have a little knowledge of reflection. Today I sorted it out in detail.

1. How to get the object of Class

  • Class.forName("full class name"): Load the bytecode file into memory and return the class object

    Mostly used in configuration files, define the class name in the configuration file, read the file, and load the class

  • Class name.class: Obtained by the attribute class of the class name

    Mostly used for parameter transfer

  • Object.getclass(): The getclass() method is defined in the object class

    The way to get bytecode mostly used for objects

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

Insert picture description here

2. Function of Class Object

2.1 Get function

  1. Get member variables

    • Field[] getFields(): Get all public variables
    • Field getField(string name): Get the public variable of the specified name
    • Field[] getDeclaredFields(): Get all member variables
    • Field getDeclaredField(string name): Get the variable with the specified name
		Class testClass = Test.class; // 获取类对象
		Field field = testClass.getDeclaredField("name"); // 获取变量
		field.setAccessible(true); // 解除私有
		Test test = new Test();
		Object string = field.get(test); // 获取私有的值
		System.out.println("我是原来的:" + string);
		field.set(test, "lr"); // 修改私有的值
		Object string1 = field.get(test);
		System.out.println("我是后来的:" + string1);
  1. Get construction method

    • constructor<?>getconstructors()
    • Constructorgetconstructor(类<?>…parameterTypes)
    • Constructor getDeclaredConstructor(类<?>… parameterTypes)
    • constructor<?>getDeclaredconstructors()
		Class testClass = Test.class; // 获取类对象
		Constructor constructor = testClass.getConstructor(String.class); // 获取构造方法
		Object test = constructor.newInstance("张三"); // 实例化赋予初值
		System.out.println(test);
  1. Get member method

    • Method[]getMethods()
    • Method getHethod(string name,类<?>… parameterTypes)
    • Method[l getDeclaredMethods()
    • Method getDeclaredMethod(string name,类<?>… parameterTypes)
		Class testClass = Test.class; // 获取类对象
		Test test = new Test(); 
		Method method = testClass.getMethod("test", int.class); // 放入实例化和参数
		method.invoke(test, 1); // 运行该方法
  1. Get class name

    • String.getName()
  2. Field: member variable

    • Set value
      set()
    • Get value
      get()
    • Ignore the access permission modifier
      setAccessible(true)
  3. Constructor: construction method

    • Create object
      • newInstance(Object… initargs)
  4. Method: Method object

    • Execution method
      • Object invoke(Object obj, Object… args)
    • Get method name
      • String getName: Get method name

3. Case

  • Requirements: Write a framework that can help us create objects of any class and execute any of its methods without changing any code of the class
  • achieve
    1. Configuration file
    2. reflection
  • step
    1. Define the full class name of the object to be created and the method to be executed in the configuration file
    2. Load and read configuration files in the program
    3. Use reflection technology to load class files into memory
    4. Creation method
    5. Execution method

Reflect.Class

package fanshe;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Properties;

public class Reflect {
    
    
	public static void main(String[] args) throws Exception {
    
    
		// 创建对象
		Properties properties = new Properties();
		// 获取类的加载器,可以找到src下的文件
		ClassLoader classLoader = Reflect.class.getClassLoader();
		// 读入文件
		InputStream stream = classLoader.getResourceAsStream("pro.properties");
		// 传入字节流
		properties.load(stream);

		// 获取配置文件中数据
		String className = properties.getProperty("className");
		String methodName = properties.getProperty("methodName");

		// 加载该类进内存
		Class cls = Class.forName(className);
		// 创建对象、实例化
		Object obj = cls.newInstance();

		Method method = cls.getDeclaredMethod(methodName);
		method.invoke(obj);

	}
}

pro.properties

className=fanshe.Person
methodName=sleep

Guess you like

Origin blog.csdn.net/qq_40915439/article/details/108741628