Java reflection: the soul of the framework

Reflection: the design soul of the frame

  • Framework: semi-finished software. Software development can be carried out on the basis of the framework, simplifying coding

    Before understanding the concept of reflection, we must first understand the three stages that java code goes through in the computer, as shown below
    Insert picture description here

  • Reflection: Encapsulate the various components of the class into other objects. This is the reflection mechanism.
    As shown in the figure above, the member variables name and age are encapsulated into Field objects; the construction method is encapsulated into Constructor objects; the member methods are encapsulated into Method objects , This is the reflection mechanism

    • benefit:

      1. These objects can be manipulated during the running of the program, as shown below:

        Many available methods jump out behind String str, this is the picture above
        Insert picture description here

      2. Can be decoupled to improve the scalability of the program

  • How to get the Class object

    1. Class.forName("full class name");: Load the bytecode file into memory

      The full class name, that is, the name of the package should be included when writing the class name

      • Mostly used for configuration files, the last case is an example
    2. Class name.Class: Obtained by the attribute class of the class name

      Used in the Class object stage

      • Mostly used for parameter transfer
    3. Object.getClass(): The getClass() method is defined in the Object class

      • Mostly used to obtain bytecode for objects
  • Conclusion: The same bytecode file (*.class) will only be loaded once during a program run, and the Class object obtained by any method is the same
  • Class object function:

    • Get function:
      1. Get member variables
        • Field[] getFields(): Get all public modified member variables

        • Field getField(String name): Get the public modified member variable of the specified name

        • Field[] getDeclaredFields()

        • Field getDeclaredField(String name)

      2. Get the constructors
        • Constructor<?>[] getConstructors();
        • Constructor getConstructor(类<?>… parameterTypes)
        • Constructor<?>[] getDeclaredConstructors();
        • Constructor getDeclaredConstructor(类<?>… parameterTypes)
      3. Get member methods
        • Method[] getMethods()
        • Method getMethod(String name,类<?>… parameterTypes)
        • Method[] getDeclaredMethods()
        • Method getDeclaredMethod(String name,类<?>… parameterTypes)
      4. Get the class name
        • String getName()
  • Field: member variable

    • operating

      1. Settings

        • get(Object obj)
      2. Get value

        • set(Object obj)
      3. Ignore checks for access modifiers

        • setAccessible(true)
  • Constructor: Constructor

    • Create an object:

      • T newInstance(Object… initargs)

      • If you use the empty parameter constructor to create the object, the operation can be simplified: the newInstance method of the Class object

  • Method: Method object

    • Implementation method:

      • Object invoke(Object obj,Object… args)
    • Get method name

      • String getName();
  • Case:

    • Requirements: Write a "framework" that can help us create objects of any class and execute any method without changing any code

      • 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 the configuration file in the program
        3. Use reflection technology to load files into memory
        4. Create an object
        5. Execution method
        package top.faroz.reflect;
        
        import top.faroz.domain.Person;
        import top.faroz.domain.Student;
        
        import java.io.IOException;
        import java.io.InputStream;
        import java.lang.reflect.Method;
        import java.util.Properties;
        
        /**
         * @ClassName ReflectTest
         * @Description 反射的实操
         * @Author FARO_Z
         * @Date 2020/8/15 12:45 上午
         * @Version 1.0
         **/
        public class ReflectTest {
                  
                  
            public static void main(String[] args) throws Exception {
                  
                  
                /**
                 * 可以创建任意类的对象,可以执行任意方法
                 * 前提:不能改变该类的任何代码,可以创建任意类的对象,可以执行任意方法
                 * 比如说下面这段代码
                 */
        //        Person person = new Person();
        //        person.eat();
        //
        //        Student student = new Student();
        //        student.sleep();
                /**
                 * 对不同的对象进行新建、调用方法,每次都要写新的代码,不符合上述的要求
                 * 但是,反射可以解决以上问题
                 */
        
                //1.加载配置文件
                    //1.1创建Properties对象
                Properties pro = new Properties();
                    //1.2加载配置文件,转换为一个集合
                        //1.2.1获取class目录下的文件位置
                ClassLoader classLoader = ReflectTest.class.getClassLoader();
                InputStream is = classLoader.getResourceAsStream("pro.properties");
                pro.load(is);
        
                //2.获取配置文件中定义的数据
                String ClassName=pro.getProperty("ClassName");
                String MethodName = pro.getProperty("MethodName");
        
                //3.加载该类进内存
                Class cls = Class.forName(ClassName);
                //4.创建对象
                Object obj = cls.newInstance();
                //5.获取方法对象
                Method method = cls.getMethod(MethodName);
                //6.执行方法
                method.invoke(obj);
            }
        }
        
        

Guess you like

Origin blog.csdn.net/weixin_44062380/article/details/108016935