The reflection mechanism is a key feature of Java becoming a dynamic language, in which a running Java program examines itself, or "introspection," and can directly manipulate the internal properties of the program, which allows the program to obtain information about any class of a known name through the Reflection API at execution time. And can change the content or execution method of the member variables of the class at execution time.
Reflection Package: java.lang.reflect.* Constructor (constructor) method (method) Filed (property)
There are three ways to get a class object:
(1) through Class.forName ("full class name")
such as: Class temp=class.forname ("Com.xupt.entity.User");
(2) Call the Class property of a category to get the corresponding class object.
For example: Person.class need to be aware of: need to guide the package in
(3) Call the GetClass () method of the object.
such as: User Use=new user (); Use.getclass ();
Get and view the construction methods in the class:
Constructor[] Cons=c1.getdeclaredconstructors (); for (Constructor con:cons) { System.out.println ( Arrays.tostring (Con.getparametertypes ())); }
To produce an object through a constructor:
Constructor Con=c1.getconstructor (string.class,int.class); Object obj=con.newinstance ("hehe", 2);
Use method to get the specifics of all the methods in the class:
Method[] Methods=c1.getdeclaredmethods (); for (Method method:methods) { System.out.println (method.getreturntype ());//The return value information for the method System.out.println (Method.getname ());//The name of the method System.out.println (arrays.tostring ( Method.getparametertype ()));//method parameter information}//call related method M=c1.getdeclaredmethod ("CC", Int.class),//"CC" for method name, if no parameter, The int.class does not need to write m.setaccessible (true);//can access the private modified method to invalidate the modifier. M.invoke (Obj.newinstance (1));
View all properties in a class
Field[] Fields=c1.getdeclaredfields (); for (Field field:fields) { System.out.println (Field.gettype ()); System.out.println (Field.getname ()); }
If you set a property, call the appropriate setter method to
Summary of primary Learning in Java reflection technology