[Java reflection mechanism] _ notes for in-depth research on Java reflection mechanism
Objectives of this chapter:
Use the specified method in the reflection call class
Call setter and getter Methods Using Reflection
Directly operate attributes in the Class Using Reflection
Use reflection to operate Arrays
3.1 call methods in the class through reflection
Public method getmethod (string name, class <?>... Parametertypes) throws nosuchmethodexception, securityexception
Get the method object of a method through the getmethod method, and then execute the method through this method object. However, when calling a method, the parameter issue in the method will be involved, therefore, when getmethod is used, you must set the required parameter type.
Package Org. lxh. demo15; interface China {// define the China interface public static final string National = "China"; // define the global constant public static final string author = "Li Xinghua "; // define the global constant public void saychina (); // Public String sayhello (string name, int age) without parameters and return values ); // define the method with two parameters and return the content} public class person implements China {private string name; private int age; Public Person () {// No parameter construction} public person (string na Me) {This. name = Name; // set the name attribute} public person (string name, int age) {This (name); this. age = age;} public void saychina () {// override method system. out. println ("Author:" + author + ", nationality:" + national);} Public String sayhello (string name, int age) {return name + ", hello! I am: "+ age +" years old! ";} Public void setname (string name) {This. name = Name;} public void setage (INT age) {This. age = age;} Public String getname () {return this. name;} public int getage () {return this. age ;}};
Call the saychina () method because this method does not have any parameters.
Method for executing the call:
Public object invoke (Object OBJ, object... ARGs) throws illegalaccessexception, illegalargumentexception, invocationtargetexception
During execution, parameters must also be passed in, and objects must be instantiated.
Package org. lxh. demo15.invokedemo; import java. Lang. Reflect. method; public class invokesaychinademo {public static void main (string ARGs []) {class <?> C1 = NULL; try {C1 = Class. forname ("org. lxh. demo15.person "); // instantiate the Class Object} catch (exception e) {}try {method met = c1.getmethod (" saychina "); // locate the saychina () method met. invoke (c1.newinstance (); // call method} catch (exception e) {e. printstacktrace ();}}}
If a parameter exists in the method to be called, you must set the parameter type and content.
Package org. lxh. demo15.invokedemo; import java. Lang. Reflect. method; public class invokesayhellodemo {public static void main (string ARGs []) {class <?> C1 = NULL; try {C1 = Class. forname ("org. lxh. demo15.person "); // instantiate the Class Object} catch (exception e) {}try {method met = c1.getmethod (" sayhello ", String. class, Int. class); // find the saychina () method string Rv = NULL; Rv = (string) met. invoke (c1.newinstance (), "Li Xinghua", 30); // call the method system. out. println (RV);} catch (exception e) {e. printstacktrace ();}}};
3.2 call setter and getter classes through reflection
The setter and getter methods are standard attribute access methods. If a class attribute is encapsulated, it must be set and obtained through the setter and getter methods, in fact, the reason for the operation of this method is that the reflection mechanism can provide support.
You can call the setter and getter methods through reflection.
If you want to call setter, for example, set the name attribute, write the setname () method, and the first letter of the second word of the method must be capitalized.
Package org. lxh. demo15.invokedemo; import java. Lang. Reflect. method; public class invokesetgetdemo {public static void main (string ARGs []) {class <?> C1 = NULL; object OBJ = NULL; try {C1 = Class. forname ("org. lxh. demo15.person "); // instantiate the Class Object} catch (exception e) {}try {OBJ = c1.newinstance ();} catch (exception e) {} setter (OBJ, "name", "Li Xinghua", String. class); // call the setter method setter (OBJ, "Age", 30, Int. class); // call the setter method system. out. print ("name:"); getter (OBJ, "name"); system. out. print ("Age:"); getter (OBJ, "Age");}/** object OBJ: the object to be operated string Att: Operation attribute object Value: class of the attribute content to be set <?> Type: attribute type to be set */public static void setter (Object OBJ, string ATT, object value, class <?> Type) {try {method met = obj. getclass (). getmethod ("set" + initstr (ATT), type); // get the setter method met. invoke (OBJ, value); // set the setter content} catch (exception e) {e. printstacktrace () ;}} public static void getter (Object OBJ, string ATT) {try {method met = obj. getclass (). getmethod ("get" + initstr (ATT); // obtain the setter method system. out. println (met. invoke (OBJ); // call getter to get content} catch (exception e) {e. printstacktrace () ;}} public static string initstr (string old) {// uppercase string STR = old. substring (0, 1 ). touppercase () + Old. substring (1); Return STR ;}};3.3 call attributes through reflection
If you want to operate on the attributes of a class, you can also use filed, so you do not have to bother using setter and getter. Get public attributes:
Public field getfield (string name) throws nosuchfieldexception, securityexception
Get the attributes of this class:
Public field getdeclaredfield (string name) throws nosuchfileexception, securityexception
Get attribute content:
Public object get (Object OBJ) throws illeaglargumentexception, illegalaccessexception
Set attributes:
Public void set (Object OBJ, object Value) throws illeaglargumentexception, illegalaccessexception
When accessing a private property, you must make this property visible:
Public void setaccessible (Boolean flag) throws securityexception
Set the content to true.
Package org. lxh. demo15.invokedemo; import java. Lang. Reflect. Field; public class invokefielddemo {public static void main (string ARGs []) throws exception {class <?> C1 = NULL; object OBJ = NULL; C1 = Class. forname ("org. lxh. demo15.person "); // instantiate the Class Object OBJ = c1.newinstance (); field namefield = NULL; field agefield = NULL; namefield = c1.getdeclaredfield (" name "); // obtain the name attribute agefield = c1.getdeclaredfield ("Age"); // obtain the name attribute namefield. setaccessible (true); // This attribute is externally visible to agefield. setaccessible (true); // This attribute is externally visible to namefield. set (OBJ, "Li Xinghua"); // sets the name attribute content agefield. set (OBJ, 30); // set the age attribute content system. out. println ("name:" + namefield. get (OBJ); system. out. println ("Age:" + agefield. get (OBJ ));}};
However, check whether the setter and getter methods of the class are supported in the above operations? It is proved that the above operation call is irrelevant to setter and getter, but to ensure program security, it is best to use setter and getter methods to complete the call.
3.3 operate arrays through reflection
The reflection mechanism can be used not only in the class, but also in any referenced data type. Of course, this includes arrays, which are completed using the array class.
The class contains the following method:
Public class <?> Getcomponenttype ()
Obtain the content of the specified object in the array:
Public static object get (Object array, int index) throws illegalargumentexception, arrayindexoutofboundsexception
Modification content:
Public static void set (Object array, int index, object Value) throws illegalargumentexception, arrayindexoutofboundsexception
Open up new Arrays:
Public static object newinstance (class <?> Componenttype, Int... dimensions) throws illegalargumentexception, negativearraysizeexception
Obtain the array information and modify the array content:
Package Org. lxh. demo15.invokedemo; import Java. lang. reflect. array; public class changearraydemo {public static void main (string ARGs []) throws exception {int temp [] = {1, 2, 3 }; // declare an integer array int newtemp [] = (INT []) arrayinc (temp, 5); // re-open space 5 print (newtemp); system. out. println ("\ n -----------------------"); string T [] = {"lxh", "mldn", "mldnjava"}; string nt [] = (string []) arrayinc (T, 8); print (NT );} Public static object arrayinc (Object OBJ, int Len) {class <?> C = obj. getclass (); Class <?> Arr = C. getcomponenttype (); // get the object newo = array of the array. newinstance (ARR, Len); // open up the new size int CO = array. getlength (OBJ); system. arraycopy (OBJ, 0, newo, 0, CO); // copy the return newo;} public static void print (Object OBJ) {// array output class <?> C = obj. getclass (); If (! C. isarray () {// determines whether it is an array return;} class <?> Arr = C. getcomponenttype (); system. out. println (ARR. getname () + "the length of the array is:" + array. getlength (OBJ); // output array information for (INT I = 0; I <array. getlength (OBJ); I ++) {system. out. print (array. get (OBJ, I) + ","); // output through array }}};