Training 28 2018/5/5

reflection

  The JAVA reflection mechanism is that in the running state, for any class, you can know all the properties and methods of the class; for any object, you can call any of its methods and properties; this dynamically obtained information and dynamic call The function of the method of the object is called the reflection mechanism of the java language . To dissect a class, you must first obtain the bytecode file object of the class . The anatomy uses the methods in the Class class. Therefore, the object of the Class type corresponding to each bytecode file must be obtained first.

  ClassThere is no public constructor. ClassObjects are automatically constructed by the Java virtual machine when a class is loaded and by calling defineClassmethods .

  

  As a preparatory work, first write the Person class for demonstration purposes:

 

//Person.java

public  class Person {
     // Member variable 
    public String name;
     public  int age;
     private String address;

    // Constructor 
    public Person() {
        System.out.println( "Empty parameter constructor" );
    }
    
    public Person(String name) {
        this.name = name;
        System.out.println( "Constructor with String" );
    }
    // Private constructor 
    private Person(String name, int age){
         this .name = name;
         this .age = age;
        System.out.println( "Constructor with String, int" );
    }
    
    public Person(String name, int age, String address){
        this.name = name;
        this.age = age;
        this.address = address;
        System.out.println( "Constructor with String, int, String" );
    }
    
    // Member method
     // Method with no return value and no parameters 
    public  void method1(){
        System.out.println( "Method with no return value and no parameters" );
    }
    // No return value, method with parameters 
    public  void method2(String name){
        System.out.println( "No return value, method with parameters name= "+ name);
    }
    // There is a return value, no parameters 
    public  int method3(){
        System.out.println( "Method with return value, no parameter" );
         return 123 ;
    }
    // Method with return value and parameter 
    public String method4(String name){
        System.out.println( "method with return value and parameter" );
         return "haha" + name;
    }
    // Private method 
    private  void method5(){
        System.out.println( "Private method" );
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + ", address=" + address+ "]";
    }
}

 

 

 

  There are three ways to get the Class class object:

    Method 1: Through the getObject() method in the Object class

Person p=new Person;

Class c=p.getObject();

    Method 2 : Get the bytecode file object through class name.class (any data type has a class static attribute)

 

Class c2 = Person.class;

 

    Method 3: Through the method in the Class class (pass the class name as a string to the static method forName() in the Class class) [commonly used]

Class c3=Class.forName("Person");

  Note:

    The difference between the third and the first two: When using the first two, you must specify the Person type, while the third is to specify a string of this type.

 

  Get the constructor via reflection and use:

    In the reflection mechanism, the members of the class (construction method, member method, member variable) are encapsulated into the corresponding class for representation.

    Get the constructor: getConstructor()

    Get multiple constructors: getConstructors()

    

public  class ConstructorDemo {
     public  static  void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
         // 1, get the Class object 
        Class c = Class.forName("cn.itcast_01_Reflect.Person "); // package name.class name
         // 2, get the specified constructor
         // public Person()
         // Constructor con = c.getConstructor(null);
        
        //public Person(String name, int age, String address)
        Constructor con = c.getConstructor(String.class, int.class, String.class);
        
        // 3, Create an object through the Constructor method in the constructor class
         // Object obj = con.newInstance(null); 
        Object obj = con.newInstance("Xiao Ming", 22, "Harbin" );
        
        // Display 
        System.out.println(obj);
    }
}

    Through reflection, you can get private constructors and create objects (doing so destroys one of the characteristics of object-oriented: encapsulation) - use the setAccessible() method:

      To obtain a private constructor, the steps are as follows:

      1. Get the Class object

      2. Get the specified constructor

      3. Brute-force access, through the setAccessible (boolean flag) method

      4. Create an object through the method in the constructor class Constructor public T newInstance(Object... initargs)

  Get member variables via reflection and use:

    In the reflection mechanism, the member variables in the class are represented by the class Field. Member variables can be obtained through the methods provided in the Class class.

    getField(String name) Get the specified public-modified variable

    getDeclaredField(String name) Get the specified variable (any modification can be obtained, that is, violent acquisition)

    getFields() gets all public modified variables

    getDeclaredFields() gets all variables (including private ones)

    

    To get member variables, the steps are as follows:

    1. Get the Class object

    2. Get the constructor

    3. Create objects by constructing methods

    4. Get the specified member variable (private member variable, brute force access through the setAccessible (boolean flag) method)

    5. Assign values ​​or get values ​​to the specified member variables of the specified object through methods - set(), get()

  

  Get member methods via reflection and use:

    In the reflection mechanism, the member methods in the class are represented by the class Method. Member methods are available through methods provided in the Class class.

    getMethod() gets the public modified method

    getDeclaredMethod() to get arbitrary methods (including private ones)

    getMethods() Get all public modified methods in this class and the parent class

    getDeclaredMethods() Get all methods in this class (including private ones)

    

    To get the member method, the steps are as follows:

    1. Get the Class object

    2. Get the constructor

    3. Create objects by constructing methods

               4. Get the specified method

               5. Execute the found method - invoke()

      

    To get a private member method, the steps are as follows:

    1. Get the Class object

    2. Get the constructor

    3. Create objects by constructing methods

    4. Get the specified method

    5. Enable brute force access

    6. Execute the found method - invoke()

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325378517&siteId=291194637