Location>code7788 >text

Java reflection mechanism

Popularity:558 ℃/2025-02-19 19:12:38

What is reflection

Official definition: The ability to dynamically obtain class information at runtime and operate class attributes and methods(No need to know the specific details of this class in advance).Simply put, suppose you have a box filled with toys. The normal operation is: you know what toys are in the box and you can take them out directly. Reflection operation: Explore the box with your eyes closed, through the shape, What weight is toy

The effect of reflection

  • The core role of reflection: dynamic.Reflection allows the program to operate classes and objects dynamically at runtime, rather than writing dead code at compile time. It is like installing a "scanner" to the program, which can monitor unknown class structures in real time.

Basic implementation of reflection: Class object

Class objects are simply "id cards" of the class

  • For each class, for exampleString,ArrayList), There is a corresponding Class object in the JVM, which records all messages of this class including: class name, method, field, constructor, etc.

  • More appropriate analogy

    Suppose you want to assemble a computer

    • Category: Design drawings equivalent to computer
    • Object: A physical computer made from drawings
    • Class object: the index card of the drawing (record, location of the drawing, version number, required part information)

    If you want to view the drawings, instead of operating the drawings directly,Instead, find the drawing information through the index card (Class object)

Methods to get Class object

Class name.class

//Class name.class (most direct)
         Class<String> stringClass = ;
  • It is clear that the class to be operated, and check whether the class exists during compilation

Object.getClass()

//Object.getClass()
         String str = "Hello World";
         Class<?> strClass = ();
  • The prerequisite is that there is an object instance, and you can only get the Class of the object instance type

()

//("full class name") The most flexible
         Class<?> arrayListClass = ("");
  • Dynamically load the class (depending on the configuration), the input type must be completed (package name + class name)

The main function of Class objects

Through the Class object, we can "dissect a class"

  • Create an object:Create a class name even if you don't know
  • View class information:Including class name, package name, parent class information, interface, etc.
  • Get all methods and fields: Even private methods
  • Calling method:Includes private methods
  • Dynamic operation field values

Class object obtain constructor method

Get the constructor method

  • Constructor<?>[] getConstructors(): Get all public constructor methods

    //Get all public constructors of the class
             Constructor<?>[] constructors = ();
  • Constructor<?>[] getDeclaredConstructors(): Get all constructors including private

    //Get all constructors of the class including private
             Constructor<?>[] declaredConstructors = ();
  • Constructor<T> getConstructor(Class<?>... paramTypes): Get the constructor without parameters or with parameters

    //Get the parameterless constructor public
             Constructor<Student> classConstructor = ();
  • Constructor<T> getDeclaredConstructor(Class<?>... paramTypes):A constructor for obtaining any access permissions

    //Get the parameter constructor private, and you need to pass in the Class object of parameter type
             Constructor<Student> declaredConstructor = ();
             (true);//Set access permissions to true

Methods to create objects through constructors

  • T newInstance(Object... args)

    • Create an instance using the constructor:
    //Create an object without parameter constructor
             Constructor<Student> constructor = ();
             Student student = ();
    
             //Create an object with parameter constructor
             Constructor<Student> constructor1 = (, );
             Student student1 = ("Zhang San", 18);

Field operations

  • Get fields

    • Field[] getFields(): Get all public fields, including parent class

      //Get all public fields
               Field[] fields = ();
    • Field[] getDeclaredFields(): Get all fields in this class, including private

      //Get all fields in this class including private fields
               Field[] declaredFields = ();
    • Field getField(String name): Get the public field with the specified name

      //Get the public field with the specified name
               Field name = ("name");
    • Field getDeclaredField(String name): Get any access field

      //Get any access field
               Field age = ("age");
  • Operation field value

    • Object get(Object obj): Get field value

              Field age = ("age");
              (true);
      				 Integer num = (Integer) (student);
      
    • void set(Object obj,Object value:Modify field value

      Student student = new Student();
               Field nameField = ("name");
      
               (true);//Break through access permissions
               (student, "zhangsan");

Method Operation

  • How to get it

    • Method[] getMethods(): Get all public methods

      //Get all public methods including parent class
               Method[] methods = ();
    • Method[] getDeclaredMethods(): Get all methods including private

      //Get all private methods
               Method[] declaredMethods = ();
    • Method[] getMethod(String name,Class<?>... paramTypes)Get the public method of the specified parameter

      //Get the public method of the specified parameter
               Method setName = ("setName", );
               Method setAge = ("setAge", );
    • Method[] getDeclaredMethod(String name,Class<?>... paramTypes)

      // Method to obtain any access permission
               Method getName = ("getName");
               (true);
  • Calling methods

    • Object invoke(Object obj, Object... args):Calling method

              Student student = new Student();
              Method getName = ("getName");
              String name = (String) (student);
      

Case understanding

Encapsulate a general method, which supports the incoming of various object types to implement corresponding methods

/*
      * @description: Encapsulate a general method, and supports various object types to implement corresponding methods
      * @author: HYJ
      * @date: 2025/2/17 10:25
      * @param: [className, methodName]
      * @return: void
      **/
     public static void invoke(String className, String methodName) {

         try {
             //Get Class object
             Class<?> clazz = (className);
             //Get the constructor
             Constructor<?> constructor = ();

             //Instantiate the object
             Object instance = ();

             //Get method
             Method method = (methodName);

             //Calling the method's invoke execution method
             (instance);
         } catch (Exception e) {
             ();
         }
     }