The Java reflection mechanism is in the running state. For any class, all attributes and methods of the class can be obtained. For any object, any method of the class can be called; this kind of dynamically obtained information and the function of dynamically calling object methods is called the reflection mechanism of Java language.
Summary:
Reflection is a technology that allows you to get objects (classes, attributes, and methods) by name.
For example, we can use a class name to generate an instance of a class;
If you know the method name, you can call this method. If you know the attribute name, you can access the value of this attribute.
1. Get the class object corresponding to the class
Use (known object) getclass (): Method in the object class, each class has this method.
For example, string STR = new string ();
Class strclass = Str. getclass (); Use (class of a known subclass) class. getsuperclass (): The method in the class, returns the class of the class's parent class; Use (known class full name): class. forname () Static Method usage (known class): Class Name. class
2. Construct a class instance by Class Name
A. Call a constructor without parameters:
Class newoneclass = Class. forname (class full name); newoneclass. newinstance ();
B. Call a constructor with parameters: We can customize a function.
Public object newinstance (string classname, object [] ARGs) throws exception {
// ARGs is a parameter Array
Class newoneclass = Class. forname (classname); // obtain the class array of the parameter (an array composed of the classes of each parameter), thereby deciding to call the constructor class [] argsclass = new class [args. length]; for (INT I = 0, j = args. length; I <j; I ++) {argsclass [I] = ARGs [I]. getclass ();
}
Constructor cons = newoneclass. getconstructor (argsclass); // select the return cons. newinstance (ARGs) Function Based on argsclass; // instantiate an object based on specific parameters.
}
3. Get the attributes of an object
A. Non-static attributes: first obtain the class, then obtain the field of the class, and then call the field with the specific instance as the parameter.
Public object getproperty (Object owner, string fieldname) throws exception {class ownerclass = owner. getclass (); // first obtain the class field = ownerclass. getfield (fieldname); // then obtain the field of this class. You can also use getfields () to obtain all Field object property = field. get (owner); // The owner points out that this attribute value of the instance is obtained. If this attribute is not public, illegalaccessexception is reported here.
Return property;
}
B. Static attributes:
The last step is different. Because the static property belongs to this class, you only need to call this field on this class to get object property = field. Get (ownerclass );
4. Execute methods for an object
Public object invokemethod (Object owner, string methodname, object [] ARGs) throws exception {class ownerclass = owner. getclass (); // It is also the class array for getting parameters from the class. It is equivalent to the type array for getting the parameter list, depending on which function we choose.
Class [] argsclass = new class [args. length]; for (INT I = 0, j = args. length; I <j; I ++) {argsclass [I] = ARGs [I]. getclass ();
}
// Select a function based on the function name and function type
Method method = ownerclass. getmethod (methodname, argsclass); Return method. Invoke (owner, argS); // This function is called under a specific parameter value under a specific instance.
}
5. Static execution methods
Similar to the above, but the last line does not need to specify a specific instance
Return method. Invoke (null, argS );
6. Determine whether it is an instance of a class
Public Boolean isinstance (Object OBJ, class CLs) {return Cls. isinstance (OBJ );
}
Test Bean class: simplebean. Java
Java code
Package com. royzhou. Bean;
Public class simplebean {
Private string name;
Private string [] holobby;
Public simplebean (){
}
Public simplebean (string name, string [] holobby) {This. Name = Name; this. holobby = holobby;
}
Public void setname (string name ){
This. Name = Name;
}
Public String getname (){
Return this. Name;
}
Public void setholobby (string [] holobby ){
This. holobby = holobby;
}
Public String [] getholobby (){
Return this. holobby;
}
Public String tostring (){
String returnvalue = super. tostring () + "\ n"; returnvalue + = "Name: =" + this. Name + "\ n"; if (this. holobby! = NULL ){
Returnvalue + = "holobby :";
For (string S: This. holobby) {returnvalue + = S + ",";
}
Returnvalue + = "\ n ";
}
Return returnvalue;
}
}
Package com. royzhou. Bean;
Public class simplebean {
Private string name;
Private string [] holobby;
Public simplebean (){
}
Public simplebean (string name, string [] holobby) {This. Name = Name; this. holobby = holobby;
}
Public void setname (string name ){
This. Name = Name;
}
Public String getname (){
Return this. Name;
}
Public void setholobby (string [] holobby ){
This. holobby = holobby;
}
Public String [] getholobby (){
Return this. holobby;
}
Public String tostring (){
String returnvalue = super. tostring () + "\ n"; returnvalue + = "Name: =" + this. Name + "\ n"; if (this. holobby! = NULL ){
Returnvalue + = "holobby :";
For (string S: This. holobby) {returnvalue + = S + ",";
}
Returnvalue + = "\ n ";
}
Return returnvalue;
}
}
Reflection test class: reflecttest. Java
Java code
Package com. royzhou. Bean;
Import java. Lang. Reflect. constructor; import java. Lang. Reflect. Field; import java. Lang. Reflect. method;
Public class reflecttest {
Public static void main (string [] ARGs) throws exception {
Class clazz = simplebean. Class;
// Instantiate the bean using a non-argument Constructor
Simplebean sb = (simplebean) clazz. newinstance (); system. Out. println (SB );
// Use the constructor with parameters to instantiate the bean
Constructor = clazz. getconstructor (new class [] {string. class, string []. class}); sb = (simplebean) constructor. newinstance (new object [] {"royzhou", new string [] {"football", "basketball"}); system. out. println (SB );
// Set the value for the name field
Field field = clazz. getdeclaredfield ("name"); field. setaccessible (true); // avoid private access and throw an exception field. set (SB, "maid"); system. out. println ("Modify name using field: =" + sb. getname () + "\ n ");
// List all methods of simplebean class
Method [] Methods = clazz. getdeclaredmethods (); system. Out. println ("Get methods of class simplebean :");
For (method: Methods ){
If ("setholobby". Equals (method. getname ())){
// Dynamically call the method of the class to set the value for holobby
Method. Invoke (SB, new object [] {New String [] {"tennis", "Fishing "}});
}
System. Out. println (method. getname ());
}
System. Out. println ("\ NSET by invoke method"); system. Out. println (SB );
}
}
Package com. royzhou. Bean;
Import java. Lang. Reflect. constructor; import java. Lang. Reflect. Field; import java. Lang. Reflect. method;
Public class reflecttest {
Public static void main (string [] ARGs) throws exception {
Class clazz = simplebean. Class;
// Instantiate the bean using a non-argument Constructor
Simplebean sb = (simplebean) clazz. newinstance (); system. Out. println (SB );
// Use the constructor with parameters to instantiate the bean
Constructor = clazz. getconstructor (new class [] {string. class, string []. class}); sb = (simplebean) constructor. newinstance (new object [] {"royzhou", new string [] {"football", "basketball"}); system. out. println (SB );
// Set the value for the name field
Field field = clazz. getdeclaredfield ("name"); field. setaccessible (true); // avoid private access and throw an exception field. set (SB, "maid"); system. out. println ("Modify name using field: =" + sb. getname () + "\ n ");
// List all methods of simplebean class
Method [] Methods = clazz. getdeclaredmethods (); system. Out. println ("Get methods of class simplebean :");
For (method: Methods ){
If ("setholobby". Equals (method. getname ())){
// Dynamically call the method of the class to set the value for holobby
Method. Invoke (SB, new object [] {New String [] {"tennis", "Fishing "}});
}
System. Out. println (method. getname ());
}
System. Out. println ("\ NSET by invoke method"); system. Out. println (SB );
}
}
Output result:
Com. royzhou. Bean. simplebean @ 757aef
Name: = NULL
Com. royzhou. Bean. simplebean @ d9f9c3
Name: = maid
Holobby: football, basketball,
Modify name using field: = maid
Get methods of class simplebean:
Setholobby
Getholobby
Getname
Tostring
Setname
Set by invoke Method
Com. royzhou. Bean. simplebean @ d9f9c3
Name: = maid
Holobby: tennis, fishing,