java reflection base

The original text is reproduced from http://blog.csdn.net/sinat_38259539/article/details/71799078.


!!!!


Reflection is the soul of frame design

(Prerequisite for use: you must first get the Class of the bytecode represented, which is used to represent the. class file (bytecode))

I. Overview of Reflection

JAVA reflection mechanism is in the running state, for any class, can know all the attributes and methods of this class; for any object, can call any of its methods and attributes; this dynamic acquisition of information and the function of dynamic invocation of the method of the object is called the reflection mechanism of Java language.
To dissect a class, you must first obtain the bytecode file object of that class. Anatomy uses methods in Class classes. So first, we need to get objects of Class type corresponding to each bytecode file.


The above summary is what reflection is.
Reflection is mapping various components of a Java class into one Java object after another.
For example, a class has information such as member variables, methods, construction methods, packages and so on. Using reflection technology, a class can be dissected and its components can be mapped into objects.
(Actually, in a class, there is a class to describe these member methods, construct methods, and add classes)
Figure 1 shows the normal loading process of a class: the principle of reflection is with the class object.
Familiarize yourself with loading: Class objects are designed to read class files into memory and create a Class object for them.



This Class object is very special. Let's look at this Class class first.

2. Look at the API details of Class classes in java (API 1.7)

How to read the api in java? See the basic of Java - String string processing



Instances of Class classes represent classes and interfaces in running Java applications. That is to say, there are more than N instances in jvm, and each class has the Class object. (Including basic data types)
Class has no common constructor. Class objects are automatically constructed by the Java virtual machine when loading classes and by calling the defineClass method in the class loader. That is to say, we don't need to deal with the creation by ourselves. JVM has already created it for us.

Without a common method of construction, there are 64 too many methods. Which of the following will be explained in detail



3. Use of Reflections (demonstrated here with Student class)

Write a Student class first.

1. Three Ways to Get Class Objects

1.1 Object -> getClass();
1.2 Any data type (including basic data types) has a "static" class attribute
1.3 Static methods through Class classes: forName (String className) (commonly used)


1.1 is due to the getClass method in the Object class, because all classes inherit the Object class. So call the Object class to get it


  1. <span style="font-size:18px;">package fanshe;  
  2. /** 
  3.  * Three Ways to Get Class Objects 
  4.  * 1 Object -> getClass(); 
  5.  * 2 Any data type (including basic data types) has a "static" class attribute 
  6.  * 3 Static methods through Class classes: forName (String className) (commonly used) 
  7.  * 
  8.  */  
  9. public class Fanshe {  
  10.     public static void main(String[] args) {  
  11.         //The first way to get a Class object  
  12.         Student stu1 = new Student();//This new produces a Student object, a Class object.  
  13.         Class stuClass = stu1.getClass();//Get the Class object  
  14.         System.out.println(stuClass.getName());  
  15.           
  16.         //The second way to get Class objects  
  17.         Class stuClass2 = Student.class;  
  18.         System.out.println(stuClass == stuClass2);//Determine whether the Class object acquired in the first way is the same as the object acquired in the second way?  
  19.           
  20.         //The third way to get Class objects  
  21.         try {  
  22.             Class stuClass3 = Class.forName("fanshe.Student");//Note that this string must be a real path, that is, the class path with the package name, the package name, the class name  
  23.             System.out.println(stuClass3 == stuClass2);//Determine whether the same Class object is acquired in three ways  
  24.         } catch (ClassNotFoundException e) {  
  25.             e.printStackTrace();  
  26.         }  
  27.           
  28.     }  
  29. }</span>  

Note: During runtime, only one Class object is generated for a class.

Three ways are commonly used in the third way, the first object has to reflect what to do. The second is packages that need to import classes, which rely too heavily on throwing compilation errors without importing packages. Generally, there is a third way, a string can be passed in or written in the configuration file, and many other methods.

2. Obtain the construction method by reflection and use:

Studdent class:
  1. package fanshe;  
  2.   
  3. public class Student {  
  4.       
  5.     //Constructing method-------------------------------------------------------------------------------------  
  6.     //(Default construction method)  
  7.     Student(String str){  
  8.         System.out.println("(default)Construction method s = " + str);  
  9.     }  
  10.       
  11.     //Parametric-free construction method  
  12.     public Student(){  
  13.         System.out.println("Called the public, parametric construction method to execute...");  
  14.     }  
  15.       
  16.     //A Method of Constructing a Parameter  
  17.     public Student(char name){  
  18.         System.out.println("Full name:" + name);  
  19.     }  
  20.       
  21.     //A Method of Constructing Multiple Parameters  
  22.     public Student(String name ,int age){  
  23.         System.out.println("Full name:"+name+"Age:"+ age);//There are some problems in the efficiency of implementation, which will be solved later.  
  24.     }  
  25.       
  26.     //Protected Construction Method  
  27.     protected Student(boolean n){  
  28.         System.out.println("Protected Construction Method n = " + n);  
  29.     }  
  30.       
  31.     //Private Construction Method  
  32.     private Student(int age){  
  33.         System.out.println("Private Construction Method   Age:"+ age);  
  34.     }  
  35.   
  36. }  

There are six construction methods.

Test class:
  1. package fanshe;  
  2.   
  3. import java.lang.reflect.Constructor;  
  4.   
  5.   
  6. /* 
  7.  * Through the Class object, we can get the construction method, member variable and member method of a class, and access members. 
  8.  *  
  9.  * 1.Get the construction method: 
  10.  *      1).Batch method: 
  11.  *          public Constructor[] getConstructors(): All "public" construction methods 
  12.             public Constructor[] getDeclaredConstructors(): Get all constructions (private, protected, default, public) 
  13.       
  14.  *      2).Get a single method and call: 
  15.  *          public Constructor getConstructor(Class... parameterTypes):Get a single "public" construction method: 
  16.  *          public Constructor getDeclaredConstructor(Class... parameterTypes):Getting "a constructor" can be private, protected, default, and public; 
  17.  *       
  18.  *          Call the constructor: 
  19.  *          Constructor-->newInstance(Object... initargs) 
  20.  */  
  21. public class Constructors {  
  22.   
  23.     public static void main(String[] args) throws Exception {  
  24.         //1. Loading Class Objects  
  25.         Class clazz = Class.forName("fanshe.Student");  
  26.           
  27.           
  28.         //2. Get all public constructions  
  29.         System.out.println("**********************All public construction methods*********************************");  
  30.         Constructor[] conArray = clazz.getConstructors();  
  31.         for(Constructor c : conArray){  
  32.             System.out.println(c);  
  33.         }  
  34.           
  35.           
  36.         System.out.println("************All construction methods(Including: Private, Protected, Default, Public)***************");  
  37.         conArray = clazz.getDeclaredConstructors();  
  38.         for(Constructor c : conArray){  
  39.             System.out.println(c);  
  40.         }  
  41.           
  42.         System.out.println("*****************A Constructive Approach to Acquiring Public Ownership and No Parameters*******************************");  
  43.         Constructor con = clazz.getConstructor(null);  
  44.         //1>, because it is a parametric construction method, the type is a null, and it can be written without: what is needed here is a parameter type, remember that it is a type.  
  45.         //2>, returns the class object describing the parametric constructor.  
  46.       
  47.         System.out.println("con = " + con);  
  48.         //Call the constructor  
  49.         Object obj = con.newInstance();  
  50.     //  System.out.println("obj = " + obj);  
  51.     //  Student stu = (Student)obj;  
  52.           
  53.         System.out.println("******************Get the private constructor and call it*******************************");  
  54.         con = clazz.getDeclaredConstructor(char.class);  
  55.         System.out.println(con);  
  56.         //Call the constructor  
  57.         con.setAccessible(true);//Violent access (ignoring access modifiers)  
  58.         obj = con.newInstance('male');  
  59.     }  
  60.       
  61. }  

Background output:
  1. **********************All public construction methods*********************************  
  2. public fanshe.Student(java.lang.String,int)  
  3. public fanshe.Student(char)  
  4. public fanshe.Student()  
  5. ************All construction methods(Including: Private, Protected, Default, Public)***************  
  6. private fanshe.Student(int)  
  7. protected fanshe.Student(boolean)  
  8. public fanshe.Student(java.lang.String,int)  
  9. public fanshe.Student(char)  
  10. public fanshe.Student()  
  11. fanshe.Student(java.lang.String)  
  12. *****************A Constructive Approach to Acquiring Public Ownership and No Parameters*******************************  
  13. con = public fanshe.Student()  
  14. Called the public, parametric construction method to execute...  
  15. ******************Get the private constructor and call it*******************************  
  16. public fanshe.Student(char)  
  17. Name: Male  

Call method:
1. Obtain the construction method:
1. Batch method:
public Constructor[] getConstructors(): All "public" construction methods
Public Constructor [] getDeclared Constructors (): Get all constructions (private, protected, default, public)
     
2) Get a single method and call:
public Constructor getConstructor(Class... parameterTypes): Get a single "public" constructor:
Public Constructor getDeclared Constructor (Class... parameterTypes): Getting "a constructor" can be private, or protected, default, or public;

Call the constructor:
Constructor-->newInstance(Object... initargs)

2. newInstance is the method of Constructor class (the class that manages constructors)
The api is interpreted as:
newInstance(Object... initargs)
Create a new instance of the declarative class of the Constructor using the Constructor object representation and initialize the instance with the specified initialization parameters.
Its return value is of type T, so newInstance is a new instance object that creates a declarative class of constructors. And call for it

3. Get member variables and call them

Studdent class:
  1. <span style="font-size:14px;">package fanshe.field;  
  2.   
  3. public class Student {  
  4.     public Student(){  
  5.           
  6.     }  
  7.     //**************** Field***************************//  
  8.     public String name;  
  9.     protected int age;  
  10.     char sex;  
  11.     private String phoneNum;  
  12.       
  13.     @Override  
  14.     public String toString() {  
  15.         return "Student [name=" + name + ", age=" + age + ", sex=" + sex  
  16.                 + ", phoneNum=" + phoneNum + "]";  
  17.     }  
  18.       
  19.       
  20. }</span>  


Test class:
  1. <span style="font-size:14px;">package fanshe.field;  
  2. import java.lang.reflect.Field;  
  3. /* 
  4.  * Get member variables and call: 
  5.  *  
  6.  * 1.Batch 
  7.  *      1).Field[] getFields():Get all "public fields" 
  8.  *      2).Field[] getDeclaredFields():Get all fields, including: private, protected, default, public; 
  9.  * 2.Get a single: 
  10.  *      1).public Field getField(String fieldName):Gets a "public" field; 
  11.  *      2).public Field getDeclaredField(String fieldName):Get a field (which can be private) 
  12.  *  
  13.  *   Set the value of the field: 
  14.  *      Field --> public void set(Object obj,Object value): 
  15.  *                  Description of parameters: 
  16.  *                  1.obj:The object of the field to be set; 
  17.  *                  2.value:The value to set for the field; 
  18.  *  
  19.  */  
  20. public class Fields {  
  21.   
  22.         public static void main(String[] args) throws Exception {  
  23.             //1. Getting Class Objects  
  24.             Class stuClass = Class.forName("fanshe.field.Student");  
  25.             //2. Get fields  
  26.             System.out.println("************Get all public fields********************");  
  27.             Field[] fieldArray = stuClass.getFields();  
  28.             for(Field f : fieldArray){  
  29.                 System.out.println(f);  
  30.             }  
  31.             System.out.println("************Get all fields(Including private, protected, default)********************");  
  32.             fieldArray = stuClass.getDeclaredFields();  
  33.             for(Field f : fieldArray){  
  34.                 System.out.println(f);  
  35.             }  
  36.             System.out.println("*************Get public fields**And call***********************************");  
  37.             Field f = stuClass.getField("name");  
  38.             System.out.println(f);  
  39.             //Get an object  
  40.             Object obj = stuClass.getConstructor().newInstance();//Generate Student Object - "Student stu = new Student();  
  41.             //Set values for fields  
  42.             f.set(obj, "Lau Andy");//Assign the name attribute in the Student object - "stu.name = Andy Lau"  
  43.             //Verification  
  44.             Student stu = (Student)obj;  
  45.             System.out.println("Verify name:" + stu.name);  
  46.               
  47.               
  48.             System.out.println("**************Get private fields****And call********************************");  
  49.             f = stuClass.getDeclaredField("phoneNum");  
  50.             System.out.println(f);  
  51.             f.setAccessible(true);//Violent Reflex, Release Private Limitation  
  52.             f.set(obj, "18888889999");  
  53.             System.out.println("Verification telephone:" + stu);  
  54.               
  55.         }  
  56.     }</span><span style="font-size:18px;">  
  57. </span>  

Background output:

  1. ********************** Access to all public fields******************
  2. public java.lang.String fanshe.field.Student.name  
  3. ******************** Get all fields (including private, protected, default)**************************
  4. public java.lang.String fanshe.field.Student.name  
  5. protected int fanshe.field.Student.age  
  6. char fanshe.field.Student.sex  
  7. private java.lang.String fanshe.field.Student.phoneNum  
  8. ******************* Gets the public field** and calls the public field*********************************************************************************************
  9. public java.lang.String fanshe.field.Student.name  
  10. Verify Name: Andy Lau
  11. ************************** Gets private fields****** and calls********************************
  12. private java.lang.String fanshe.field.Student.phoneNum  
  13. Verification call: Student [name = Andy Lau, age=0, sex=

Thus it can be seen
When calling a field: you need to pass two parameters:
Object obj = stuClass.getConstructor().newInstance(); // Generate Student Objects - > Student stu = new Student();
// Set values for fields
f.set(obj, "Andy Lau"); // assign a value to the name attribute in the Student object - "stu.name = Andy Lau"
The first parameter: to pass in the set object, the second parameter: to pass in the argument

4. Get member methods and call them

Studdent class:
  1. <span style="font-size:14px;">package fanshe.method;  
  2.   
  3. public class Student {  
  4.     //************************ Membership Method***************************//  
  5.     public void show1(String s){  
  6.         System.out.println("Called: public, String Parametric show1(): s = " + s);  
  7.     }  
  8.     protected void show2(){  
  9.         System.out.println("Called: Protected, parametric show2()");  
  10.     }  
  11.     void show3(){  
  12.         System.out.println("Called: default, no parameters show3()");  
  13.     }  
  14.     private String show4(int age){  
  15.         System.out.println("Called, private, and has a return value, int Parametric show4(): age = " + age);  
  16.         return "abcd";  
  17.     }  
  18. }  
  19. </span>  

Test class:
  1. <span style="font-size:14px;">package fanshe.method;  
  2.   
  3. import java.lang.reflect.Method;  
  4.   
  5. /* 
  6.  * Get the member method and call: 
  7.  *  
  8.  * 1.Batch: 
  9.  *      public Method[] getMethods():Get all "public methods"; (methods that contain parent classes also contain Object classes) 
  10.  *      public Method[] getDeclaredMethods():Get all member methods, including private (excluding inheritance) 
  11.  * 2.Get a single: 
  12.  *      public Method getMethod(String name,Class<?>... parameterTypes): 
  13.  *                  Parameters: 
  14.  *                      name : Method name; 
  15.  *                      Class ... : Class-TYPE OBJECTS WITH FORMAL PARAMETERS 
  16.  *      public Method getDeclaredMethod(String name,Class<?>... parameterTypes) 
  17.  *  
  18.  *   Call method: 
  19.  *      Method --> public Object invoke(Object obj,Object... args): 
  20.  *                  Description of parameters: 
  21.  *                  obj : Objects to call methods; 
  22.  *                  args:The argument passed in the invocation mode; 
  23.  
  24. ): 
  25.  */  
  26. public class MethodClass {  
  27.   
  28.     public static void main(String[] args) throws Exception {  
  29.         //1. Getting Class Objects  
  30.         Class stuClass = Class.forName("fanshe.method.Student");  
  31.         //2. Get all public methods  
  32.         System.out.println("***************Getting all the "public" methods*******************");  
  33.         stuClass.getMethods();  
  34.         Method[] methodArray = stuClass.getMethods();  
  35.         for(Method m : methodArray){  
  36.             System.out.println(m);  
  37.         }  
  38.         System.out.println("***************Get all the methods, including private ones*******************");  
  39.         methodArray = stuClass.getDeclaredMethods();  
  40.         for(Method m : methodArray){  
  41.             System.out.println(m);  
  42.         }  
  43.         System.out.println("***************Acquisition of public ownership show1()Method*******************");  
  44.         Method m = stuClass.getMethod("show1", String.class);  
  45.         System.out.println(m);  
  46.         //Instantiate a Student object  
  47.         Object obj = stuClass.getConstructor().newInstance();  
  48.         m.invoke(obj, "Lau Andy");  
  49.           
  50.         System.out.println("***************Getting Private show4()Method******************");  
  51.         m = stuClass.getDeclaredMethod("show4"int.class);  
  52.         System.out.println(m);  
  53.         m.setAccessible(true);//Release of Private Limitation  
  54.         Object result = m.invoke(obj, 20);//Two parameters are required, one is the object to be invoked (get reflections) and the other is the argument.  
  55.         System.out.println("Return value:" + result);  
  56.           
  57.           
  58.     }  
  59. }  
  60. </span>  
Console output:
  1. ***************Getting all the "public" methods*******************  
  2. public void fanshe.method.Student.show1(java.lang.String)  
  3. public final void java.lang.Object.wait(long,intthrows java.lang.InterruptedException  
  4. public final native void java.lang.Object.wait(longthrows java.lang.InterruptedException  
  5. public final void java.lang.Object.wait() throws java.lang.InterruptedException  
  6. public boolean java.lang.Object.equals(java.lang.Object)  
  7. public java.lang.String java.lang.Object.toString()  
  8. public native int java.lang.Object.hashCode()  
  9. public final native java.lang.Class java.lang.Object.getClass()  
  10. public final native void java.lang.Object.notify()  
  11. public final native void java.lang.Object.notifyAll()  
  12. ***************Get all the methods, including private ones*******************  
  13. public void fanshe.method.Student.show1(java.lang.String)  
  14. private java.lang.String fanshe.method.Student.show4(int)  
  15. protected void fanshe.method.Student.show2()  
  16. void fanshe.method.Student.show3()  
  17. ***************Acquisition of public ownership show1()Method*******************  
  18. public void fanshe.method.Student.show1(java.lang.String)  
  19. Called: public, String Parametric show1(): s = Lau Andy  
  20. ***************Getting Private show4()Method******************  
  21. private java.lang.String fanshe.method.Student.show4(int)  
  22. Called, private, and has a return value,intParametric show4(): age = 20  
  23. Return value: abcd  

Thus it can be seen:
M = stuClass. getDeclared Method ("show4", int. class); / / / Call Formulation Method (all private) needs to pass in two parameters, the first is the name of the method invoked, the second is the parameter type of the method, remember the type.
System.out.println(m);
m.setAccessible(true); //Release of private definitions
Object result = m.invoke(obj, 20); // Two parameters are required, one is the object to be invoked (retrieved with reflection) and the other is the argument.
System.out.println("return value:" +result);)//

Console output:
  1. ***************Getting all the "public" methods*******************  
  2. public void fanshe.method.Student.show1(java.lang.String)  
  3. public final void java.lang.Object.wait(long,intthrows java.lang.InterruptedException  
  4. public final native void java.lang.Object.wait(longthrows java.lang.InterruptedException  
  5. public final void java.lang.Object.wait() throws java.lang.InterruptedException  
  6. public boolean java.lang.Object.equals(java.lang.Object)  
  7. public java.lang.String java.lang.Object.toString()  
  8. public native int java.lang.Object.hashCode()  
  9. public final native java.lang.Class java.lang.Object.getClass()  
  10. public final native void java.lang.Object.notify()  
  11. public final native void java.lang.Object.notifyAll()  
  12. ***************Get all the methods, including private ones*******************  
  13. public void fanshe.method.Student.show1(java.lang.String)  
  14. private java.lang.String fanshe.method.Student.show4(int)  
  15. protected void fanshe.method.Student.show2()  
  16. void fanshe.method.Student.show3()  
  17. ***************Acquisition of public ownership show1()Method*******************  
  18. public void fanshe.method.Student.show1(java.lang.String)  
  19. Called: public, String Parametric show1(): s = Lau Andy  
  20. ***************Getting Private show4()Method******************  
  21. private java.lang.String fanshe.method.Student.show4(int)  
  22. Called, private, and has a return value,intParametric show4(): age = 20  
  23. Return value: abcd  

In fact, the member methods here: there is the word attribute in the model, which is the setter () method and getter() method. There are also fields, which are detailed in the introspection.

5. Reflective main method

Studdent class:
  1. <span style="font-size:14px;">package fanshe.main;  
  2.   
  3. public class Student {  
  4.   
  5.     public static void main(String[] args) {  
  6.         System.out.println("main The method is executed...");  
  7.     }  
  8. }  
  9. </span>  


Test class:
  1. <span style="font-size:14px;">package fanshe.main;  
  2.   
  3. import java.lang.reflect.Method;  
  4.   
  5. /** 
  6.  * Get the main method of the Student class and don't get confused with the current main method 
  7.  */  
  8. public class Main {  
  9.       
  10.     public static void main(String[] args) {  
  11.         try {  
  12.             //1. Getting bytecode of Student object  
  13.             Class clazz = Class.forName("fanshe.main.Student");  
  14.               
  15.             //2. Obtaining main method  
  16.              Method methodMain = clazz.getMethod("main", String[].class);//The first parameter is the method name, and the second parameter is the type of the method parameter.  
  17.             //3. Call main method  
  18.             // methodMain.invoke(null, new String[]{"a","b","c"});  
  19.              //The first parameter, the object type, is null because the method is static, and the second parameter is String array. Note that when jdk1.4 is an array, after jdk1.5 is a variable parameter.  
  20.              //new String []{a,""b,""c"} is split into three objects when it is disassembled here. So we need to turn it around.  
  21.              methodMain.invoke(null, (Object)new String[]{"a","b","c"});//One way  
  22.             //methodMain.invoke(null, new Object[]{new String []{a,""b,""c"});//Mode 2  
  23.               
  24.         } catch (Exception e) {  
  25.             e.printStackTrace();  
  26.         }  
  27.           
  28.           
  29.     }  
  30. }</span><span style="font-size:18px;">  
  31. </span>  

Console output:
The main method executes...

6. Other uses of reflection methods - running configuration file content by reflection

Studdent class:
  1. public class Student {  
  2.     public void show(){  
  3.         System.out.println("is show()");  
  4.     }  
  5. }  

The configuration file takes the txt file as an example (pro.txt):
  1. className = cn.fanshe.Student  
  2. methodName = show  

Test class:
  1. import java.io.FileNotFoundException;  
  2. import java.io.FileReader;  
  3. import java.io.IOException;  
  4. import java.lang.reflect.Method;  
  5. import java.util.Properties;  
  6.   
  7. /* 
  8.  * Using reflection and configuration files, we can make it possible to update the application without any modifications to the source code. 
  9.  * We just need to send the new class to the client and modify the configuration file. 
  10.  */  
  11. public class Demo {  
  12.     public static void main(String[] args) throws Exception {  
  13.         //Getting Class Objects by Reflection  
  14.         Class stuClass = Class.forName(getValue("className"));//"cn.fanshe.Student"  
  15.         //2 Get show() method  
  16.         Method m = stuClass.getMethod(getValue("methodName"));//show  
  17.         //3. Call show() method  
  18.         m.invoke(stuClass.getConstructor().newInstance());  
  19.           
  20.     }  
  21.       
  22.     //This method receives a key and gets the corresponding value in the configuration file.  
  23.     public static String getValue(String key) throws IOException{  
  24.         Properties pro = new Properties();//Objects to get configuration files  
  25.         FileReader in = new FileReader("pro.txt");//Get the input stream  
  26.         pro.load(in);//Loading the stream into the configuration file object  
  27.         in.close();  
  28.         return pro.getProperty(key);//Returns the value obtained by key  
  29.     }  
  30. }  

Console output:
is show()

Demand:
When we upgrade the system, instead of the Student class, we need to write a new Student 2 class, and then we just need to change the file content of pro.txt. The code doesn't need to be changed at all.

The student2 class to replace:
  1. public class Student2 {  
  2.     public void show2(){  
  3.         System.out.println("is show2()");  
  4.     }  
  5. }  

Change the configuration file to:
  1. className = cn.fanshe.Student2  
  2. methodName = show2  
Console output:
is show2();

7. Other uses of reflection methods - passing generic checks by reflection

Generics are used at compile time and erased after compilation. So it's possible to pass generic checking by reflection.
Test class:
  1. import java.lang.reflect.Method;  
  2. import java.util.ArrayList;  
  3.   
  4. /* 
  5.  * Override generic checking by reflection 
  6.  *  
  7.  * For example, if you have a collection of String generics, how can you add an Integer type value to that collection? 
  8.  */  
  9. public class Demo {  
  10.     public static void main(String[] args) throws Exception{  
  11.         ArrayList<String> strList = new ArrayList<>();  
  12.         strList.add("aaa");  
  13.         strList.add("bbb");  
  14.           
  15.     //  strList.add(100);  
  16.         //Get the Class es object of ArrayList, invoke the add() method in reverse, and add data  
  17.         Class listClass = strList.getClass(); //Get the bytecode object of the strList object  
  18.         //Get the add() method  
  19.         Method m = listClass.getMethod("add", Object.class);  
  20.         //Call the add() method  
  21.         m.invoke(strList, 100);  
  22.           
  23.         //Ergodic set  
  24.         for(Object obj : strList){  
  25.             System.out.println(obj);  
  26.         }  
  27.     }  
  28. }  

Console output:
aaa
bbb
100

// Reflections come to a conclusion. The introspection chapters below are also related to reflection. They can be regarded as advanced use of reflection. If you are interested, you can continue to look at the introspection part of the summary.


Keywords: Java Attribute jvm

Added by trulyafrican on Sat, 18 May 2019 03:20:16 +0300