Under normal circumstances, you need to first introduce a complete class path before generating instance session objects in a fixed format, however, Java allows you to find the complete information of a class through an instance object. This is the function of the Class.
In fact, the class is the source of Java reflection. In fact, the so-called reflection is also very understandable from the running results of the program, that is, the class name can be obtained through the reflection of the object.
Instantiate the Class and there are three methods to obtain bytecode files:
First: The forName () method; Second: class. class; Third: object. getClass ()
Package toto. learn;
Class X1 {}
Publicclass GetClassDemo02 {
Publicstaticvoid main (String [] args ){
Class c1 = null; // specify the generic type
Class c2 = null; // specify the generic type
Class c3 = null; // specify the generic type
Try {
C1 = Class. forName ("toto. learn. X"); // The most common form. This method loads bytecode files into the memory.
} Catch (ClassNotFoundException e ){
E. printStackTrace ();
}
C2 = new X1 (). getClass (); // use the method instance in the Object class
C3 = X1.class; // instantiated by class
System. out. println ("Class Name:" + c1.getName (); // obtain the class name.
System. out. println ("Class Name:" + c2.getName (); // obtain the class name.
System. out. println ("Class Name:" + c3.getName (); // obtain the class name.
}
}
The package name + class name is obtained through the above method.
If you want to instantiate objects of other classes through the Class itself, you can use the newInstance () method, but you must ensure that there must be a method without parameters in the instantiated Class.
The class of the instantiated object must have a non-argument constructor. If it does not exist, it cannot be instantiated.
1. Use getConstructors () in the Class to obtain all the constructor methods in this Class.
2. Pass an array of objects to the constructor, which contains the parameters required by the constructor.
3. The object is then instantiated through the Constructor.
Package org. lxh. demo15.instancedemo;
Import java. lang. reflect. Constructor;
Publicclass InstanceDemo03 {
Publicstaticvoid main (String [] args ){
Class c = null;
Try {
C = Class. forName ("org. lxh. demo15.instancedemo. Person"); // declare a Class Object
} Catch (ClassNotFoundException e ){
E. printStackTrace ();
}
Person per = null; // declare the Person object
Constructor cons [] = null; // declare an array that represents the Constructor.
Cons = c. getConstructors (); // obtain all structures through reflection
Try {// pass parameters to the constructor. This method receives parameters using variable parameters and instantiates objects.
Per = (Person) cons [0]. newInstance ("Li Xinghua", 30 );
} Catch (Exception e) {// The array subscript is 0 because there is only one structure.
E. printStackTrace ();
}
System. out. println (per); // output object
}
}
Per = (Person) cons [0]. newInstance ("Li Xinghua", 30); // This is the part that calls and uses the constructor.
When declaring an object array, you must consider the type order of parameters in the constructor. Therefore, the type of the first parameter is Stirng, and the type of the second parameter is WieInteger (you can automatically unpack it when using it)
Constructorcons [] = null; // instantiate an array of constructor Methods
Cons = c. getConstructors (); // obtain all structures
// Pass parameters to the constructor. This method receives the request using variable parameters and instantiates the object.
Per = (Person) cons [0]. newInstance ("Li Xinghua", 30 );
Set parameters of the constructor.
PublicPerson (String name, int age) {// sets the attribute content by constructing
}
Reflection Application
You can use reflection to obtain all the Implemented interfaces.
You can use reflection to obtain the parent class inherited by a class.
You can use reflection to obtain all constructor methods in a class.
You can use reflection to obtain all the methods in a class.
You can use reflection to obtain all attributes of a class.
In actual development, the above program is the place where the reflection application is the most. Of course, the reflection mechanism provides far-reaching functions. You can also get the complete structure of a class through reflection, therefore, we need to use java. lang. several Classes in the reflect package.
Constructor: indicates the Constructor in the class.
Field: indicates the attributes in the class.
Method: indicates the Method in the class.
All three classes are subclasses of the AccessibleObject class.
To obtain all the interfaces implemented in a Class, you must use the getInterfaces () method in the Class. This method is defined as follows:
PublicClass [] getInterfaces ();
This method returns an array of objects of the Class. Then, you can directly use the getName () method in the Class to output the array.
Obtain all interfaces implemented through reflection
Package org. lxh. demo15;
Publicclass GetInterfaceDemo {
Publicstaticvoid main (String [] args ){
Class c1 = null; // declare a Class Object
Try {
C1 = Class. forName ("org. lxh. demo15.Person"); // instantiate a Class Object
} Catch (ClassNotFoundException e ){
E. printStackTrace ();
}
Class c [] = c1.getInterfaces (); // gets all the Implemented interfaces
For (int I = 0; I
System. out. println ("implemented Interface Name:" + c [I]. getName (); // output interface Name
}
}
}
Multiple Interfaces can be implemented in a Class, but only one parent Class can be inherited. To obtain the parent Class of a Class, you can directly use the getSuperclass () method in the Class. This method is defined as follows:
PublicClass getSuperclass ()
This method returns a Class instance, which is the same as the previously obtained interface and can be obtained through the getName () method.
Example of obtaining the constructor:
Package org. lxh. demo15;
Import java. lang. reflect. Constructor; // import the reflection operation package
Publicclass GetConstructorDemo01 {
Publicstaticvoid main (String [] args ){
Class c1 = null; // declare a Class Object
Try {
C1 = Class. forName ("org. lxh. demo15.Person ");
} Catch (ClassNotFoundException e ){
E. printStackTrace ();
}
Constructor con [] = c1.getConstructors (); // obtain all the Constructor methods.
For (int I = 0; I
System. out. println ("constructor:" + con [I]); // print the output directly.
}
}
}
Restore Modifier
A certain number is used to represent the Modifier of the method in Java. To restore the number to a keyword that the user can understand, the Modifier class must be used, this class is defined in java. lang. in the reflect package. Directly use the Modifer class's following method modifier:
Publicstatic String toString (int mod)
Int mo = con [I]. getModifiers ();
System. out. print (Modifier. toString (mo) + "); // restore the permission
GetDeclaredMethods () Method. This Method returns an array of objects in the Method class. If you want to further obtain the specific information of the Method, such as the parameter of the Method and the thrown exception declaration, the Method class is required.
The reflection operation can also obtain all attributes in a class, but there are two different operations when obtaining attributes:
Public Field [] getFields () throwsSecurityException
Get all the attributes defined in this class: public Field [] getDeclaredFields () throws SecurityException
To use methods in the reflection call class, you can use the Method class. The procedure is as follows:
1. Use the getMethod (Stringname, Class... ParameterTypes) Method to get a Method object, and set the parameter type required for this Method operation.
2. You can use invoke to call the API and pass the parameters to be set to the method.
In the newProxyInstance () method of the Proxy class, an instance of the ClassLoader class is required. The ClassLoader actually corresponds to the Class Loader. in Java, There are mainly three types of loaders:
BootstrapClassLoader: This loader is written in C ++ and cannot be seen during development;
ExtensionClassLoader: used to load extension classes. Generally, it corresponds to classes in the jre \ lib \ ext directory;
AppClassLoader: loads the class specified by classpath, which is the most commonly used loader.
When a class is loaded twice through forName (), the class is loaded only once.
If you have the following code:
Object obj = new VipUser (); // VipUser is a sub-class of User, which inherits the User
If (obj instanceof User ){
System. out. println ("instanceof judges as a user ");
User user = (User) obj;
}
When the above instanceof code is used to determine, obj is a User, but in fact it is not. It is only a subclass of a User.
Conclusion: When instanceof is used, it is mainly used to determine whether the subsequent interfaces are implemented.
If (obj. getClass () = User. class ){
System. out. println ("getClass judgment, is a user ");
User user = (User) obj;
}
GetClass () is used to determine the exact type of an object.
Classes used later:
Package toto. learn1;
Publicclass User {
Private String name;
Private String password;
Private String gender;
Public User (String name, String password, String gender ){
Super ();
This. name = name;
This. password = password;
This. gender = gender;
}
Public User (){
Super ();
// TODO Auto-generatedconstructor stub
}
Public User (String name, String password ){
Super ();
This. name = name;
This. password = password;
}
Public String getName (){
Returnname;
}
Publicvoid setName (String name ){
This. name = name;
}
Public String getPassword (){
Returnpassword;
}
Publicvoid setPassword (String password ){
This. password = password;
}
Public String getGender (){
Returngender;
}
Publicvoid setGender (String gender ){
This. gender = gender;
}
Publicvoid run (String str, int num ){
System. out. println ("run ");
}
Publicvoid run (String name ){
System. out. println ("hello:" + name );
}
}
The following section describes the reflection.
Package toto. learn1;
Import java. lang. reflect. Constructor;
Import java. lang. reflect. Field;
Import java. lang. reflect. Method;
Import java. lang. reflect. Modifier;
Publicclass Demo2 {
/**
* Reflection
* @ ThrowsIllegalAccessException
* @ ThrowsInstantiationException
* @ ThrowsNoSuchMethodException
* @ ThrowsSecurityException
*/
Publicstaticvoid main (String [] args) throws Exception {
Class clazz = User. class;
// Constructor
// Obtain the constructor
Constructor [] cons = clazz. getConstructors ();
For (Constructor con: cons ){
// Parameter list. The conventions obtained are complete parameter types, including the package where such types are sitting.
Class [] types = con. getParameterTypes ();
System. out. println ("parameter type :");
For (Class type: types ){
System. out. println (type. getName () + "...");
}
System. out. println ();
}
// Obtain the specified constructor creation object
Try {
Object obj = clazz. newInstance (); // The construction method without parameters is called by default.
System. out. println (obj. getClass ());
} Catch (InstantiationException e ){
E. printStackTrace ();
} Catch (IllegalAccessException e ){
E. printStackTrace ();
}
/** Parameter type:
Java. lang. String...
Java. lang. String...
Parameter type:
Java. lang. String...
Java. lang. String...
Java. lang. String...
Class toto. learn1.User */
System. out. println ("-------------------------");
// Obtain the specified constructor 2. Create an object
Object obj = clazz. newInstance (); // The construction method without parameters is called by default.
Constructor constructor = clazz. getConstructor (String. class, String. class); // The Constructor has two parameters.
// String. class is because all the parameters of the constructor with year parameters in the constructor are of the String class.
User usr = (User) constructor. newInstance ("toto", "View"); // pass two parameters.
System. out. println (usr. getName () + "" + usr. getPassword (); // result: toto View
// Method
// Obtain all methods of the class
Method [] methods = clazz. getMethods ();
For (Method method: methods ){
System. out. println (method. getName ());
}
/** The class obtained through the getMethods () method contains the parent class method and obtains the common method.
* Run
Run
GetName
SetName
GetPassword
SetPassword
GetGender
SetGender
Wait
Wait
Wait
HashCode
GetClass
Equals
ToString
Notify
Policyall
**/
// If You Want To obtain all declared methods, including non-public methods, excluding inherited methods, you can use the following methods to implement them.
System. out. println ("-----------------------");
Method [] methods2 = clazz. getDeclaredMethods ();
For (Method method: methods2 ){
System. out. println (method. getName ());
}
/** The result is:
* Run
Run
GetName
SetName
GetPassword
SetPassword
GetGender
SetGender */
// Obtain the specified method and call the Method
Method runMethod = clazz. getMethod ("run", String. class);/** the first one indicates the Method to be called.
The second parameter is a variable parameter, indicating the parameter type of the method called. */
// After obtaining the method, an object must be provided for execution. The object to be executed here is User, and the example is as follows:
User usr1 = new User ();
RunMethod. invoke (usr1, "toto"); // indicates to execute the runMethod method in the usr1 object and pass a parameter to the method.
/**
* Running result: hello: toto: run (String name) in the User class; Method output result, where name is toto */
// Attributes
// Obtain the attributes of an object. Create an object first.
Object object = new User ("toto", "123", "male"); // call the constructor in User:
// Obtain the get method based on the private attributes of the object, so you must first obtain the object's bytecode file and obtain the get method through this file.
Class objectClazz = object. getClass ();
// Obtain the get Method
Method runMethod2 = clazz. getMethod ("getName"); // because this Method has no parameters, you do not need to pass parameters to it
// Execute this method and Output Parameters
Object name = runMethod2.invoke (object );
System. out. println (name); // because the name value is passed above, the returned result value is: toto
// Obtain all attributes
System. out. println ("-------------------------------");
// Field [] fields = clazz. getFields (); // This method obtains the public attribute because the User class does not have a common attribute.
Field [] fields = clazz. getDeclaredFields (); // get the declared attribute
For (Field fd: fields ){
System. out. println (fd. getName () + "attribute type:" + fd. getType ());
}
/** The result is:
* Name attribute type: class java. lang. String
Password attribute type: class java. lang. String
Gender attribute type: class java. lang. String */
// Assign a value to the object's password attribute:
User user2 = new User ();
String fieldName = "password"; // it can be processed as a variable and any attribute name can be passed.
// Getpw is the property obtained through reflection, which is actually the password
Field getpw = user2.getClass (). getDeclaredField (fieldName );
// Determine whether the attribute is private:
Int num = getpw. getModifiers (); // The returned value is an integer.
If (num = Modifier. PRIVATE) {// obtain
System. out. println ("the attribute is private ");
// Prevent the Java Virtual Machine from checking Access Permissions
// Getpw. setAccessible (true );
}
// System. out. println (getpw); // result private java. lang. Stringtoto. learn1.User. password
Getpw. set (user2, 234567); // The previous parameter indicates assigning a password to the object.
System. out. println (user2.getPassword ());
}
}
L when using the Field class to access object attributes, pay attention to the access permission issue. If the object
If the attribute is declared as private, it cannot be accessed. In this case, you need to enable the java language check.
Filed. setAccessible (true );
L Method class represents a member Method in a class
L The invoke Method can be used to call the Method representation.
Object To Method. If the called Method is static, a null value is input.
L note: differences between jdk1.4 and jdk1.5 invoke methods:
L Jdk1.5: public Object invoke (Objectobj, Object... args)
L Jdk1.4: public Object invoke (Objectobj, Object [] args)
L when an array is passed in, the virtual opportunity takes priority for backward compatibility.
Call JDK1.4