I. The cornerstone of reflection-class
1. xxx. java class is used to describe the commonalities of a class of things. There is no attribute for such things. The value of this attribute is determined by the instance object of this class, different instance objects have different attribute values. Do Java classes in Java programs belong to the same class, and can they be described using a class? The class name is class. Pay attention to the difference between the class keyword and the lower-case class keyword. What information does the class describe? Class Name, access attribute of the class, package name of the class, list of field names, list of method names, and so on. To learn reflection, you must first understand the class.
Persons --> Persons
Many Java classes --> class classes
Each Java class is an instance object of the class. Their content is different, but they have the same features. For example, there are methods, fields, parent classes, and packages.
2. The class represents the Java class. What are the corresponding instance objects?
It corresponds to the bytecode of each class in the memory (a class usually has only one bytecode in the virtual machine), such as the bytecode of the person class, the bytecode of the arraylist class, and so on.
A class is loaded into the memory by the class loader and occupies a storage space. The content in this space is the class bytecode. the bytecode of different classes is different, so their content in the memory is different. The space can be represented by objects respectively. These objects obviously have the same type. What is this type? (For example, there are methods, fields, parent classes, and packages .)
3. How to obtain the Instance Object (class type) corresponding to each bytecode)
Class Name. class, for example, system. Class
Object. getclass (), for example, new date (). getclass ()
Class. forname ("Class Name"), for example, class. forname ("Java. util. date"); // to be the full name, package name. Class Name
4. Nine predefined class instance objects:
8 basic data types (byte int short double, etc.) plus void
Int. Class = integer. Type // The Int bytecode of the basic data type encapsulated in the integer class
System. out. println ("void:" + void. class. isprimitive (); // true is the original data system. out. println ("int:" + Int. class. isprimitive (); // truesystem. out. println ("int []:" + int []. class. isprimitive (); // falsesystem. out. println ("int []:" + int []. class. isarray (); // turesystem. out. println (Int. class = integer. class); // falsesystem. out. println (Int. class = integer. type); // true
Ii. Reflection
Reflection maps various components in the Java class into corresponding Java classes. For example, a Java class is represented by an object of A Class class, and the components of a class: member variables, methods, constructor methods, packages, and other information are also represented by Java classes, just like a car is a class, the engine and gearbox in a car are also a class. It indicates that the class of the Java class obviously needs to provide a series of methods to obtain information such as variables, methods, constructor, modifier, and package, the information is represented by the instance objects of the corresponding class, such as field, method, contructor, and package.
Iii. constructor class
The constructor class represents a constructor in a class.
Obtain all the constructor methods of a class:
Example: constructor [] constructors = Class. forname ("Java. Lang. String"). getconstructors ();
Obtain a constructor:
Example: constructor = Class. forname ("Java. Lang. String"). getconstructor (stringbuffer. Class); // obtain the specified constructor according to the parameter type of the constructor.
Create an instance object:
- Common method: String STR = new string (New stringbuffer ("ABC "));
- Reflection Method: String STR = (string) constructor. newinstance (New stringbuffer ("ABC"); // The parameter type used for the obtained constructor must be the same as the original one.
Class. newinstance () method:
Example: Date = (date) class. forname ("Java. util. date"). newinstance ();
System. Out. println (date );
- In this method, the default constructor is obtained first, and then the instance object is created using this constructor.
- How is the code written in this method written? The cache mechanism is used to save the instance objects of the default constructor. (It can be seen that reflection is resource-consuming and will reduce program performance)
Iv. Field Class
The field class represents a member variable in a class.
Demonstrate how to use eclipse to automatically generate Java classes
Q: Does the obtained Field object correspond to the member variables on the class or the member variables on the object? There is only one class, and there are multiple instance objects in this class. If it is associated with an object, which object is associated? Therefore, fieldx represents the definition of X, rather than the specific X variable.
Sample Code:
Reflectpoint point = new reflectpoint (1, 7 );
Field y = Class. forname ("cn. itcast. corejava. reflectpoint"). getfield ("Y ");
System. Out. println (Y. Get (point ));
// Field x = Class. forname ("cn. itcast. corejava. reflectpoint"). getfield ("X ");
Field x = Class. forname ("cn. itcast. corejava. reflectpoint"). getdeclaredfield ("X ");
X. setaccessible (true );
System. Out. println (X. Get (point ));
Exercise: Change "B" to "A" in the string content corresponding to all string-type member variables in any object ".
public class ReflectPoint{ private int x; public int y; public String str1="blue"; private String str2="bubble"; public String str3="soso";public ReflectPoint(int x, int y){super();this.x = x;this.y = y;}public String toString(){return str1+" "+str2+" "+str3;}}
Public class reflecttest {public static void main (string [] ARGs) throws exception {// class cls1 = system. class; // system. out. println (cls1); // class clsp1 = person. class; // class clsp2 = new person (). getclass (); // system. out. println (clsp1 = clsp2); // class cls2 = Class. forname ("Java. lang. string "); // class clsp3 = Class. forname ("day01.person"); // system. out. println (clsp1 = clsp3); // system. out. println ("void:" + void. class. isprimitive (); // true // system. out. println ("int:" + Int. class. isprimitive (); // true // system. out. println ("int []:" + int []. class. isprimitive (); // false // system. out. println ("int []:" + int []. class. isarray (); // ture // system. out. println (Int. class = integer. class); // false // system. out. println (Int. class = integer. type); // trueconstructor [] constructors = string. class. getconstructors (); // obtain all constructor = string. class. getconstructor (stringbuffer. class); // get the constructor of the specified parameter // use the constructor to create an instance string S = (string. newinstance (New stringbuffer ("Java"); system. out. println (s); // The construction method without parameters in the class date = (date) class. forname ("Java. util. date "). newinstance (); system. out. println (date); reflectpoint Rp = new reflectpoint (6, 9); field fieldy = RP. getclass (). getfield ("Y"); // note that fieldy is not an object variable, but an int RPY = (integer) fieldy. get (RP); // get the variable value system based on the object. out. println (RPY); field fieldx = RP. getclass (). getdeclaredfield ("X"); // because X is private-modified fieldx. setaccessible (true); // set private variables to allow access to system. out. println (fieldx. get (RP); changestringvalue (RP); system. out. println (RP);} public static void changestringvalue (Object OBJ) {// getfields () can only obtain the Public Member field [] fields = obj. getclass (). getdeclaredfields (); // obtain all fields of the class to which the object belongs, including private for (field: fields) {If (field. getType () = Java. lang. string. class) // judge the field type {field. setaccessible (true); // non-public-modified fields are set to accessible try {string S = (string) field. get (OBJ); field. set (OBJ, S. replace ('B', 'A');} catch (illegalargumentexception e) {e. printstacktrace ();} catch (illegalaccessexception e) {e. printstacktrace ();}}}}}
V. Method
@ Method indicates a member method in a class.
Obtain a method in the class:
Example: Method charat = Class. forname ("Java. Lang. String"). getmethod ("charat", Int. Class );
@ Call method:
Common method: system. Out. println (Str. charat (1 ));
Reflection Method: system. Out. println (charat. Invoke (STR, 1 ));
What does it mean if the first parameter of the invoke () method passed to the method object is null? This method object corresponds to a static method!
@ Jdk1.4 and jdk1.5 different invoke methods:
Jdk1.5: Public object invoke (Object OBJ, object... ARGs)
Jdk1.4: Public object invoke (Object OBJ, object [] ARGs), that is, when an array needs to be passed as a parameter to the invoke method according to the jdk1.4 syntax, each element in the array corresponds to a parameter in the called method. Therefore, the code that calls the charat method can also be changed to charat by using jdk1.4. invoke ("STR", new object [] {1}) format.
Execute the main method in a Class Using Reflection
@ Write a program that can execute the main method in the class based on the class name provided by the user. After the call is completed in normal mode, you need to understand why the call should be performed in reflection mode? If reflection is used, the program can call the main method of the Class Based on your input.
@ Problem: the parameter of the main method used to start the Java program is a string array, that is, public static void main (string [] ARGs). When the main method is called through reflection, how do I pass PARAMETERS FOR THE invoke method? According to the jdk1.5 syntax, the entire array is a parameter, and according to the jdk1.4 syntax, each element in the array corresponds to a parameter. When a string array is passed as a parameter to the invoke method, which syntax does javac use? Jdk1.5 must be compatible with the jdk1.4 syntax and will be processed according to the jdk1.4 syntax, that is, the array is split into several separate parameters. Therefore, when passing parameters to the main method, the Code mainmethod. Invoke (null, new
String [] {"XXX"}), javac only treats it as the jdk1.4 syntax and does not interpret it as the jdk1.5 syntax. Therefore, the parameter type is incorrect.
@ Solution:
Mainmethod. Invoke (null, new object [] {New String [] {"XXX "}});
Mainmethod. invoke (null, (object) New String [] {"XXX"});, the compiler performs special processing and does not treat parameters as arrays during compilation, in this case, the array will not be split into several parameters.
Method mainmethod = Class. forname (ARGs [0]). getmethod ("Main", string []. class); // call the method (static null) mainmethod. invoke (null, (object) New String [] {"111", "222", "333"}); // solves a mainmethod. invoke (null, new object [] {New String [] {"111", "222", "333"}); // solution 2
Vi. array reflection
- Arrays with the same dimension and element type belong to the same type, that is, they have the same class instance object.
int []a1=new int[3]; int []a2=new int[4]; int [][]a3=new int[3][4]; String []a4=new String[3]; System.out.println(a1.getClass()==a2.getClass());//true System.out.println(a1.getClass()==a3.getClass());//false System.out.println(a1.getClass()==a4.getClass());//false
- The parent class returned by the getsuperclass () method of the array class instance object is the class corresponding to the object class.
System.out.println(a1.getClass().getSuperclass().getName());//java.lang.Object System.out.println(a2.getClass().getSuperclass().getName());//java.lang.Object System.out.println(a3.getClass().getSuperclass().getName());//java.lang.Object System.out.println(a4.getClass().getSuperclass().getName());//java.lang.Object
- Basic Types of one-dimensional arrays can be used as objects, but not as objects []. Non-basic types of one-dimensional arrays can be used as objects, it can also be used as the object [] type.
Object aObj1 = a1;Object aObj2 = a4;//Object[] aObj3 = a1; ERROR!!!Object[] aObj4 = a3;Object[] aObj5 = a4;
- The difference between int [] and string [] in the arrays. aslist () method. (For compatibility with jdk1.4, aslist (object [] OBJ) in jdk1.4 cannot process int [] and can only be processed by jdk1.5 +. As a parameter, it is received by an object)
int []a1=new int[]{1,2,3}; String []a4=new String[]{"a","b","c"}; System.out.println(Arrays.asList(a1));//[[I@422ede] System.out.println(Arrays.asList(a4));//[a, b, c]
- The array tool class is used to perform array reflection.
Public static void printobject (Object OBJ) {class CLS = obj. getclass (); If (CLS. isarray () // determines whether an array {int Len = array. getlength (OBJ); // obtain the array length for (INT I = 0; I <Len; I ++) {// obtain the Element System in the array one by one using the subscript. out. println (array. get (OBJ, I) ;}} else {system. out. println (OBJ );}}
- Question: How to obtain the element type in the array? No
Each element object needs to be retrieved, and then each object needs to be judged [arr [I]. getclass (). getname ();], because the types of each specific element can be different, for example, object [] x = new object [] {"ABC", integer. max }.