Java. Lang. Reflect package
The parent class of constructor, field, and method is accessibleobject;
Note: reflection is mainly used for the development framework, that is, the production framework;
1. Obtain the Class Object
Class <?> C = Class. forname ("classname"); throw classnotfoundexception
2. Obtain the implementation Interface
Class <?> Inters [] = C. getinterfaces ();
For (INT I = 0; I <inters. length; I ++ ){
System. Out. Print (inters [I]. getname () + ""); // The getname () method is used to obtain the interface name;
}
3. Obtain the parent class
Class <?> Superclass = C. getsuperclass (); // obtain the parent class
String name = superclass. getname (); // obtain the parent class name
Iv. Obtain the constructor
Constructor CONS [] = C. getconstructors (); // obtain the public Constructor
Constructor dcons [] = C. getdeclaredconstructors (); // obtain all Constructors
String modifier =Modifier. tostring(Cons [I]. getmodifiers (); // obtain the access permission
String name = CONS [I]. getname (); // obtain the constructor name
Class <?> Params [] = CONS [I]. getparametertypes (); // get the parameter type object
5. Obtain the Method
Method MS [] = C. getmethods (); // returnPublicAll methods, including the Inheritance Method
Method DMS [] = C. getdeclaredmethods (); // returnThis classAll methods, excluding inherited methods
Class <?> MS [I]. getreturntype ();
Class <?> Params [] = MS [I]. getparametertypes ();
String name = MS [I]. getname ();
String modifier = modifier. tostring (MS [I]. getmodifiers ());
Class <?> Ex [] = MS [I]. getexceptiontypes (); // get exception
String name = ex [I]. getname (); // get the Exception name
6. Obtain the field
Field FS [] = C. getfields ();// Obtain public attributes, including inherited attributes
Field DFS [] = C. getdeclaredfields ();// Obtain all attributes of this class
Class <?> Type = FS [I]. GetType (); // obtain the type object of the attribute
String name = FS [I]. getname (); // obtain the attribute name
String modifier = modifier. tostring (FS [I]. getmodifiers ());
7. Create an object through reflection (1)
Class <?> C = Class. forname ("person ");
Person P = (person) C.Newinstance();
(2)
Constructor con = c1.getconstructor (class... Param );
Object OBJ = con. newinstance (Object OBJ); // create an instance based on the constructor
8. Create a constructor object
Class C = Class. forname ("person ");
Constructor <?> Cons [] = C. getconstructors ();
Person P = (person) Cons [0].Newinstance("Xiazdong", 15 );
Note: If the called constructor is private, you mustC. setaccessible (true );