Reflection is the mapping of the various components in the Java class into the corresponding Java classes (primarily for framework development)
Reflection of the Cornerstone –>class class
Each class in a Java program belongs to the same thing, and the Java class name that describes the transaction is class. What information does the class describe?
- The name of the class
- Access properties of the class
- The package name that the class belongs to
- List of field names
- List of method names
- ...
How do I get the instance object (class type) corresponding to each bytecode?
1.类名.class
Class cls1 = date.class;//Get byte code
2.对象.getClass()
New Date (). GetClass ();//Get Byte code
3. Use static method Class.forName("类名")
to get the byte code of the class corresponding to the string
Class.forName ("Java.util.Date")//forname is a static method of class, it is necessary to write the name of the package when writing the class name
- If the byte code of the class has been loaded into memory, return directly
- If the JVM does not have the byte code of the class, then use the class loader to load, after loading the bytecode cache, the method returns the byte code
As a reflection of the main use of the third method, because when the framework is written without knowing the name of the user-defined class, at run time to pass a string, the string contains a class name, when the program is running temporarily passed in
String str1 = "abc"; Class cls1 = Str1.getclass (); Class cls2 = String.class; Class CLS3 = Class.forName ("java.lang.String");//must write the package name
Three ways to get the same byte code
Note 1: Byte-code comparisons Use = = instead of equals
Note 2: A Class object actually represents a type, and this type is not necessarily a class, or it may be a Java base type. For example, int is not a class, but Int.class is an object of class type.
Reflection Constructor Class: Reflection of the construction method
Class-Constructor New object
Constructor Constructor = String.class.getConstructor (Stringbuffer.class);//When you get the construction method, pay attention to the parameter type stringbufferstring str = (String) constructor.newinstance (New StringBuffer ("Hello world!") Consult the Java API, which returns a value of type object and needs to be cast to string
Field class: Reflection of member variables
- The field class represents a member variable in a class
Crow's GitHub gives a demo of the instance domain that modifies the class through the field class, and some of the code is as follows:
public static void Reffieldchange (Fieldreflect fr, String fieldName) throws exception{//use the field class to change the class's instance domain, if it is int, all set to 3, If it is of type string, change "B" in string to "c" field field = Fr.getclass (). Getdeclaredfield (fieldName); Field.setaccessible (TRUE);//Violent Reflection if (field.gettype () = = Int.class) { Field.set (FR, 3); } else if (field.gettype () = = String.class) { String string = (String) field.get (FR); String.Replace ("B", "C"); Field.set (FR, string); } else { throw new IOException (); }}
Note: Fr.getfield () can only get visible fields, and if you encounter invisible fields such as private, you should use the Getdeclaredfield () method
Filed Fieldy = Pt1.class.getDeclaredField (fieldName);
Field.get (FR) can also only get visible fields, private is not available, at this time can use the violent reflection method, first execute
Field.setaccessible (TRUE);//Violent reflexes
Re-use Field.get (FR)
Method class: Reflection of Member methods
Str1.charatmethod Methodcharat = String.class.getMethod ("CharAt", Int.class); System.out.println (Methodcharat.invoke (str1,1));
Use method to obtain a method of a class, and then use it to work with an object
Method methodCharAt.invoke(null, 1)
is a static method, because no object is required when a static method is called
To reflect member methods that receive array parameters
For example: According to the class name provided by the user, to execute the main method in the class, where the main method receives an array of parameters.
Class Testarguments{public static void Main (string[] args) {for (String Arg:args) {System.out.println (ARG);}}}
The general method of invocation is
Testarguments.main (New string[]{"Hello", "World", "!"});
The use of reflection methods (in method Class) is
Method Mainmethod = Class.forName ("Startingclassname"). GetMethod ("main", String[].class); Mainmethod.invoke (NULL, New Object[]{new string[]{"Hello", "World", "!"});
Note: The main method accepts a parameter of type string[]. In order to be compatible with the old version code that does not have the variable parameter, the main function input a parameter (a ternary array), will be automatically split into three parameters, will appear wrong number of arguments error, so to be wrapped up with object[], only split into one parameter, That is, a ternary array.
The relationship between an array's reflected array and object and its reflection type
The reflection of an array with the same data type and dimension is the same
int [] A1 = new Int[]{1,2,3};int [] a2 = new int[4];int[][] a3 = new Int[2][3]; String [] a4 = new string[]{"A", "B", "C"}; Object aObj1 = A1; Correct, because the int array is objectobject aObj2 = a4;//object[] aObj3 = A1; Error because the base type int is not objectobject[] aObj4 = A3; Correct, because the int array is objectobject[] aObj5 = A4;
The type of each element in the array can be obtained by reflection:
object[] Clsarray = new object[] ("a", 1); Clsarray[0].getclass (). GetName ();
(But I don't know how Java gets the type of array, but I'm looking for a reader to know)
Array Reflection Application Example: print all elements in an array
private static void PrintObject (Object obj) {//prints all elements of the array class clazz = Obj.getclass (); if (Clazz.isarray ()) {int len = array . GetLength (obj); for (int i=0;i<len;i++) {System.out.println (Array.get (obj, i));}} Else{system.out.println (obj);}}
Basic Java Learning (1)--reflection