java Foundation: Reflection

reflex

Running program:

  • Compile: will The java file is compiled to generate the corresponding class file (bytecode file)

  • Run: call the resource execution program of the operating system based on the bytecode file

Class loading:

  • Load bytecode files from hard disk into memory (static constant pool)

object-oriented:

  • Everything is object

  • Class attribute: characteristic method: behavior

  • Definition class: class name

Class class

  • Object class of bytecode file of current class - class representing class

  • Content contained in class:

    • Constructor, field, method and annotation, such as @ overwrite (Annotation)

Variable parameters

  • In the parameter list of the method, variable parameters can be defined so that the number of parameters of the method is determined by the caller;

  • Format: data type... Name

be careful:

  1. Only one variable parameter can be defined in the method parameter list

  2. A single parameter and a variable parameter can be defined simultaneously in the method parameter list, but the variable parameter must be placed at the end of the parameter list

public class ChangeDemo {
    public static void main(String[] args) {
        System.out.println(add(3,5));
        int[] arr = new int[]{3,1,5,7,6};
        System.out.println(add(arr));

    }

    public static int add(int ... arr){
        // Passed in as an array
        int sum = 0;
        for (int i : arr){
            sum += i;
        }
        return sum;
    }
}

advantage:

  1. Simplify the code and improve the reusability of the code;

  2. Improve the flexibility of the code;

Reflection concept

  • You can create the currently running class or the object of the interface implementation class without using new

  • Gets the Class of the Class

    • Class Class - > returns an object of type class

      Class clz = String.class;
      System.out.println(clz);  // class java.lang.String
      Class clz1 = int.class;
      System.out.println(clz1);  // int
      

      Class name Class call the class attribute of the class to get the class object of the class

    • Object The getClass() method obtains the Class object of the Class corresponding to the object

      String ss = new String();
      System.out.println(ss.getClass());  // class java.lang.String
      

      The premise is that there is an object of the current class

    • Get the Class object corresponding to the Class according to the Class name

      Class. Forname (class name of full path);

      Class clz = Class.forName("java.lang.String");
      System.out.println(clz);  // class java.lang.String
      

Class:

  • method:
    • static Class<?> Forname (string classname): returns the class object associated with the class or interface with the given string name.
    • T newInstance(): create a new instance of the Class represented by this Class object. Note: this method is only applicable to creating objects through nonparametric construction; If there is no parameterless construction in the Class, creating an object through this method will run and throw an exception (this method is outdated)
    • Get construction method:
      • Constructor < T > getconstructor (Class <? >... Parametertypes): returns a constructor object that reflects the specified public constructor of the Class represented by this Class object.
      • Constructor<?> [] getconstructors(): returns an array containing some constructor objects that reflect all public constructor methods of the Class represented by this Class object.
      • The above two methods can only return the constructor of public decoration
      • Constructor < T > getdeclaraedconstructor (Class <? >... Parametertypes): returns a constructor object that reflects the specified construction method of the Class or interface represented by this Class object.
      • Constructor<?> [] getdeclaraedconstructors(): returns an array of constructor objects that reflect all construction methods declared by the Class represented by this Class object.
    • Get properties:
      • Field getField(String name): returns a field object that reflects the specified public field of the Class or interface represented by this Class object.
      • Field[] getFields(): returns an array containing some field objects that reflect all accessible public fields of the Class or interface represented by this Class object.
      • The above two methods can only return public modified properties
      • Field getdeclaraedfield (string name): returns a field object that reflects the specified declared field of the Class or interface represented by this Class object.
      • Field [] getdeclaraedfields(): returns an array of field objects that reflect all fields declared by the Class or interface represented by this Class object.
    • Get method:
      • Method getmethod (string name, Class <? >... Parametertypes): the first parameter represents the method name, the second parameter represents the Class object of the type of the parameter list of the current method, and returns a method object that reflects the specified public member method of the Class or interface represented by this Class object.
      • Method[] getMethods(): returns an array containing some method objects that reflect the public member methods of the Class or interface represented by the Class object (including those declared by the Class or interface and those inherited from the super Class and super interface).
      • Method getdeclaraedmethod (string name, Class <? >... Parametertypes): returns a method object that reflects the specified declared method of the Class or interface represented by this Class object.
      • Method[] getDeclaredMethods(): returns an array of method objects that reflect all methods declared by the Class or interface represented by this Class object, including public, protected, default (package) access and private methods, but excluding inherited methods.

Constructor class:

  • method
    • T newInstance(Object... initargs): use the Constructor represented by this Constructor object to create a new instance of the declaration class of the Constructor, and initialize the instance with the specified initialization parameters.
    • setAccessible(boolean flag): set the flag to true to perform brute force cracking without permission control
    • Class<?> [] getexceptiontypes(): returns a group of class objects representing the exception types declared to be thrown. These exceptions are thrown by the underlying Constructor represented by the Constructor object.
    • Class<?> [] getparametertypes(): returns a group of class objects in the order of declaration, which represent the formal parameter type of the construction method represented by the Constructor object.

Field class:

  • method:
    • Object get(Object obj): returns the value of the Field represented by this Field on the specified object.
    • void set(Object obj, Object value): sets the Field represented by this Field object on the specified object variable to the specified new value.
    • Class<?> GetType (): returns a class object that identifies the declaration type of the Field represented by this Field object.

Method class:

  • method:
    • Object invoke(Object obj, Object... args): the first parameter specifies which object Method to call, and the second parameter: the value of the argument; Calls the underlying Method represented by this Method object on the specified object with the specified parameters
    • Class<?> Getreturntype(): returns a class object that describes the formal return type of the Method represented by the Method object

advantage:

  • It improves the flexibility and scalability of the code

Disadvantages:

  • You can bypass the checking of generics, which may cause problems in the use of collections

  • Break the object-oriented encapsulation

Example: simulate database operations

public class DataBaseDemo {
    public static void main(String[] args) throws Exception {
        // Load profile
        Properties properties = new Properties();
        properties.load(new FileInputStream(".\\dataBase.properties"));
        String value = properties.getProperty("DBName");
        System.out.println(value);
        // Create an object using the class name (value)
        Class clz = Class.forName(value);
        System.out.println(clz);  // class cn.ysu.reflect.MySql
        // newInstance() gets the instance of the Class corresponding to the Class object (obsolete)
        // Can only be used for parameterless constructions
        // Object o = clz.newInstance();

        // Creating objects with parametric constructs
        Constructor constructor = clz.getConstructor(String.class);
        // Get the object through newInstance() of the constructor
        Object o = constructor.newInstance("root");

        // Get private constructor
        Constructor constructor1 = clz.getDeclaredConstructor(String.class, String.class);
        System.out.println(constructor1);  // Private CN ysu. reflect. MySql(java.lang.String,java.lang.String)
        // brute force 
        constructor1.setAccessible(true);
        // Get object
        Object o1 = constructor1.newInstance("root", "123");
        System.out.println(o1); // cn.ysu.reflect.MySql@723279cf

        DataBase db = (DataBase) o;
        db.insert();

          // Get the constructor class that throws the exception <? > [] getExceptionTypes()
//        Constructor constructor = clz.getConstructor(String.class);
//        Class[] exces = constructor.getExceptionTypes();
//        for (Class c : exces){
//            System.out.println(c);  // class java.lang.Exception
//        }

        // Gets the property of the public modifier
        Field field = clz.getField("id");
        System.out.println(field);  // public java.lang.String cn.ysu.reflect.DataBase.id
        //  Object get(Object obj): gets the value of the current attribute
        Object val = field.get(o);
        System.out.println(val);  // root
        // Set the attribute value void set(Object obj, Object value)
        field.set(o,"zss");
        System.out.println(field.get(o));  // zss

        Field field2 = clz.getDeclaredField("sql");
        // brute force 
        field2.setAccessible(true);
        field2.set(o1,"SELECT * FROM student");
        Object psw = field2.get(o1);
        System.out.println(psw);  // SELECT * FROM student

        // Acquisition method
        Method method = clz.getMethod("insert");
        // To call a method, you need to specify the called object and parameter values
        method.invoke(o);
        // Get private method
        Method method1 = clz.getDeclaredMethod("delete");
        // Call method
        method1.setAccessible(true);
        // Gets an object of type value returned by the method
        Class c = method1.getReturnType();
        System.out.println(c);  // boolean
        Object oo = method1.invoke(o);
        System.out.println(oo);  // true

    }
}
abstract class DataBase{
    public String id;
    public String psw;
    public abstract void insert();
}

class MySql extends DataBase{

    private String sql;

    public MySql(String id) throws Exception {
        if (id == null){
            throw new Exception();
        }
        this.id = id;
        System.out.println("Create an object through a parameterized construct with one parameter");
    }

    private MySql(String id, String psw){
        this.psw = psw;
        this.id = id;
        System.out.println("To create an object through a parameterized construction, two parameters");
    }

    public void insert(){
        System.out.println("from Mysql Insert data into database");
    }

    private boolean delete(){
        System.out.println("from Mysql Delete data from database");
        return true;
    }
}

class Oracle extends DataBase{
    public void insert(){
        System.out.println("from Oracle Insert data into database");
    }
}

dataBase.properties file content

DBName = cn.sss.reflect.MySql

Keywords: Java Back-end

Added by jonmkim on Wed, 15 Dec 2021 11:16:51 +0200