JAVA learning course 64th-reflection mechanism and java reflection mechanism
The Java reflection mechanism is in the running state. For any class, all attributes and methods of this class can be known,Any method and attribute of an object can be called. This dynamically obtained information and the function of dynamically calling the object method is called the reflection mechanism of java language. To put it simply: it can dynamically obtain information in the class (all in the class), which is the reflection of java. It can also be understood as an anatomy of the class.
Basic application scenarios of reflection mechanisms:
For example, an application (TomCat) of a program exposes an interface to improve its scalability, and defines a class to implement this interface externally, but cannot create new objects within the application, therefore, the application will provide a configuration file. You can use the interface to write the written class name that implements the interface into the configuration file, the application uses the reflection mechanism to obtain the bytecode file of the class with the specified name and load the content to call the file. This is the basic application of the reflection mechanism.
Conclusion: The reflection technology improves the scalability of the program, and the application is simple. The bridge between the user and the program is changed to the configuration file.
To dissect a class file, you only need to obtain the bytecode file of the class.
In reality, Things constantly extract their common content to get classes to describe things. In the reflection mechanism, bytecode is also extracted upwards and Class is used to describe bytecode files, then, you can generate an object and provide a method to obtain the members of the bytecode file, such as the name, field, constructor, and general function. Reflection is based on this class.
Define demo class
public class Man {private int age;private String name;public Man() {super();System.out.println("Man run");}public Man(int age, String name) {super();this.age = age;this.name = name;System.out.println("Man run yes"+this.name+this.age);}public void show(){System.out.println(age+"..show.."+name);}private void privatemethod(){System.out.println(age+"..method.."+name);}public void print(int num,String line){System.out.println(num+"..print.."+line);}public static void staticmethod(){System.out.println("..staticmethod..");}}
How to obtain Class objects
To dissect a bytecode file, you must obtain the object of the bytecode file.
There are three methods to obtain bytecode file objects:
1. The getClass method in the Object class
In this way, you must specify a specific class and create an object.
public static void get_Class_Object() {Man man1 = new Man(); Class<?> clas1 = man1.getClass(); Man man2 = new Man(); Class<?> clas2 = man2.getClass(); System.out.println(clas1==clas2);}
2. Any data type has a static attribute. class to obtain its corresponding Class Object
Relatively simple, but it is still necessary to clarify the static members in the class, and the scalability is not high
public static void get_Class_static() {Class<?> cls1 = Man.class;Class<?> cls2 = Man.class;System.out.println(cls1==cls2);}
3. You can obtain the class by using the string name of the given class (important)
You can use methods in the Class to complete
This method is forName (); this method only requires a name.
API:forName(String className)
ReturnsClass
Object.
API:forName(String name, boolean initialize,ClassLoader loader)
Returns the class or interface associated with the given string name using the given class loader.Class
Object.
Public static void get_Class () throws ClassNotFoundException {// G: \ java \ fan \ bin \ fan \ Man. class // The default classpath path is src, binString classname = "fan. man "; // specify the Class in which package <?> Cls = Class. forName (classname); System. out. println (cls );}
Note that an exception is thrown.
Obtain the constructor in the Class.
Man man = new Man (); in the past, the new object first looks for the bytecode file of the Class Based on the name of the new class and loads it into the memory, create the bytecode file object, and then create the Man object corresponding to the bytecode file.
API:newInstance()
Create thisClassA new instance of the class represented by the object. It is similar to usingnew
This class is instantiated by expression. If the class has not been initialized, initialize the class.
It is actually the constructor of the null parameter in Man.
Empty parameter constructor in Man class
Public static void reflect_Demo () throws ClassNotFoundException, InstantiationException, IllegalAccessException {String classname = "fan. man "; // find the Class name file and load it into the memory to generate the Class Object Class <?> Cls = Class. forName (classname); Object obj = cls. newInstance ();}
There is no null parameter constructor in the Man class.
Man man = new Man (11, "");
If you call the preceding method directly, the initialization exception InstantiationException is thrown.
If there is an empty parameter constructor, but it is a private Man (){},Will throw invalid access exception IllegalAccessException
Therefore, when you get the object embodied in the specified name class, and object initialization does not use a null parameter to construct, you should first obtain its constructor, which can be completed through the bytecode file object, getConstructor
API:getConstructor(Class<?>... parameterTypes)
ReturnsConstructor
Object, which reflectsClass
Specifies the public constructor of the class represented by the object.
API:getDeclaredConstructors()
ReturnConstructor
An array of objects, which reflectClass
All constructor methods of the class declaration represented by the object.
WhileThe Constructor object contains the method new object.
API:newInstance(Object... initargs)
Use thisConstructor
Object To create a new instance of the Declaration class of the constructor, and initialize the instance with the specified initialization parameters.
Public static void reflect_Demo () throws Exception {String classname = "fan. Man"; Class <?> Cls = Class. forName (classname); // parameter array. the bytecode corresponding to an int basic data type is int. classConstructor <?> Constructor = cls. getConstructor (int. class, String. class); // obtains the Object obj = constructor. newInstance (11, "a") of the specified constructor ");}
However, when configuring the file, you must specify the parameter information of the Class Name and constructor.
PS: Generally, the reflected classes contain null parameters, because it is convenient to obtain instances.
Obtain fields in the Class
API:getField(String name)
ReturnsField
Object, which reflectsClass
The specified public member field of the class or interface represented by the object.
API:getFields()
ReturnsField
Array of objects, which reflectClass
All accessible public fields of the class or interface represented by the object.
API:getDeclaredField(String name)
ReturnsField
Object, which reflectsClass
The specified declared field of the class or interface represented by the object.
API:getDeclaredFields()
ReturnField
An array of objects, which reflectClass
All fields declared by the class or interface indicated by the object.
Public static void reflect_Demo () throws Exception {String classname = "fan. Man"; Class <?> Cls = Class. forName (classname); Object object = cls. newInstance (); // Field field = cls. getField ("name"); // contains the age and name fields. Only public Field = cls can be obtained. getDeclaredField ("name"); // only this class can be obtained, including private System. out. println (field); // obtain the field value ......... // Object obj = field. get (object); // System. out. println (obj); // The Reverse query fails because it is private. // The ACL check for private fields is canceled.-> brute force access to field. setAccessible (true); // The Field's parent class method, modifying its access permission field. set (object, "a"); // sets the Object obj = field. get (object); System. out. println (obj );//}
API: The AccessibleObject class is the base class of the Field, Method, and Constructor object. It provides the ability to mark reflected objects as canceling the default Java language access control check during use.
PS: it is not recommended to access data through brute force access.
Obtain methods in a specified Class
Obtain a method without Parameters
Public static void reflect_Demo () throws Exception {String classname = "fan. Man"; Class <?> Cls = Class. forName (classname); // Method [] methods = cls. getMethods (); // obtain all public methods of the class and its parent class. // methods = cls. getDeclaredMethods (); // only obtain all methods in this class, including private // for (Method M: methods) {// System. out. println (M); // Method = cls for a non-argument method. getMethod ("show", null); // note that unlike the constructor, the method name and method parameter list // Object obj = cls. newInstance (); // No parameter construction // method. invoke (obj, null); Constructor <?> Constructor = cls. getConstructor (int. class, String. class); Object obj = constructor. newInstance (1, "a"); // method with parameters. invoke (obj, null); // call the underlying Method represented by this Method object for the specified object with the specified parameter .}
Get the method with Parameters
Public static void reflect_Demo () throws Exception {String classname = "fan. Man"; Class <?> Cls = Class. forName (classname); Method method = cls. getMethod ("print", int. class, String. class); // method parameter list Object obj = cls. newInstance (); method. invoke (obj, 11, "a"); // call the obtained method}
Reflection exercise:
Public class Computer {public void run () {System. out. println ("Computer is run .... ");} public void UseInter (Inter p) {// exposes the interface to improve the scalability of if (p! = Null) {p. open (); p. close () ;}} public interface Inter {public void open (); public void close ();} public class NetCard implements Inter {public void open () {System. out. println ("NetCard open .... ");} public void close () {System. out. println ("NetCard close... ") ;}} public class SoundCard implements Inter {public void open () {System. out. println ("SoundCard open... ");} public void close () {System. out. println ("Sound Card close... ") ;}} public class Main {public static void main (String [] args) throws Exception {Computer com = new Computer (); com. run (); // com. useInter (new SoundCard (); // polymorphism, but in this case, you need to modify the existing code. // use the radiation mechanism to obtain the Class file, create the object File conFile = new File ("G: \ java \ fan \ bin \ fan \ inter. properties "); Properties pro = new Properties (); FileInputStream FD = new FileInputStream (conFile); pro. load (FCM); // load the information in the stream into the set for (in T x = 0; x <pro. size (); x ++) {String intername = pro. getProperty ("Inter" + (x + 1); Class <?> Cls = Class. forName (intername); // use Class to load this Inter subclass Object obj = cls. newInstance (); // create Inter object Inter p = (Inter) obj; com. useInter (p);} fiis. close ();}}
Because XML has not been learned, use properties instead.
Use of java reflection mechanism
Increase Program flexibility.
Such as struts. Request distribution control.
When the request comes. Struts queries the configuration file. Find the action corresponding to the request. The method has been used.
Then, the action is instantiated through reflection. And call the response method.
If reflection is not applicable, you can only write it to the code.
Therefore, one is flexible, and the other is not flexible.
In rare cases, non-reflection is not required. In most cases, reflection is used to improve program flexibility.
Therefore, most frameworks are used. Because the framework should be applicable in more cases. High requirements on flexibility.
Java reflection mechanism
Import java. lang. reflect. InvocationTargetException;
Import java. lang. reflect. Method;
Public class Admin {
Public Admin (){
}
Private String id = "";
Public String getId (){
System. out. print (id );
Return id;
}
Public void setId (String id ){
This. id = id;
}
Public static void main (String [] args)
Throws ClassNotFoundException, InstantiationException, IllegalAccessException,
SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
String str = "com. spring. event. Admin ";
Class c = Class. forName (str );
Object obj = c. newInstance ();
// Set the attribute value here
Method m = c. getMethod ("setId", new Class [] {Class. forName ("java. lang. String ")});
M. invoke (obj, new Object [] {"penghao122 "});
// Obtain the attribute value in
M = c. getMethod ("getId", new Class [] {});
M. invoke (obj, new Object [] {});
}
}
Import java. lang. reflect. InvocationTargetException;
Import java. lang. reflect. Method;
Public class Admin {
Public Admin (){
}
Private String id = "";
Public String getId (){
System. out. print (id );
Return id;
}
Public void setId (String id ){
This. id = id;
}
Public static void main (String [] args)
Throws ClassNotFoundException, InstantiationException, IllegalAccessException,
SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
String str = "com. spring. event. Admin ";
Class c = Class. forName (str );
Object... the remaining full text>