The reflection mechanism of Java has been understood very vague, today because of learning spring, so took some time to finally straighten it out, record
In addition, recommended reading this article, written very good http://blog.csdn.net/woshixuye/article/details/7700455
classPerson {PrivateString name; Private intAge ;//Public person (String name,int age) {//This.name=name;//This.age=age;// }@Override PublicString toString () {return"Person [name=" + name + ", age=" + Age + "]"; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } Public voidAdd () {System.out.println ("Add"); } Public voidAddwithparameters (String name,intAge ) {System.out.println ("Add with parameter method" + name +Age ); } Public Static voidSayHello () {System.out.println ("Hello"); }}1. Get Class object
Get person person=null by instance; Class<?> Personclass=person.getclass ();
get class<?> Personclass=class.forname (Com.test.Person) by Class name;
2. Instantiate an Object
The constructor is non-parametric: person person = (person) c.newinstance (); The constructor is a parameter, the constructor is obtained first, and the constructor new one instance:constructor<?> constructor=c.getconstructor (String.class,int.class); Person person= (person) constructor.newinstance ("Cold shunping", 66);
3. Call this class's static property, method, this time does not need the instance object
Method
Method=c.getmethod ("SayHello");//parameter is the name of the methods Method.invoke (NULL); Must have parameter null
4, call this class's non-static properties, non-static methods, you need to instantiate an object
does not contain parameter method Method=personclass.getmethod ("Add"); Method.invoke (Personclass.newinstance ());
parameters (constructors and calling methods are included) method Method=personclass.getmethod ("Addwithparameters", String.class,int.class); Constructor<?> Constructor=personclass.getconstructor (String.class,int.class); Method.invoke ( Constructor.newinstance ("Cold shunping", "a"), "Hello", 22);
Summary: Get the static properties of a class and the method does not need to instantiate the class, as long as the class has been loaded, you can obtain the information by the appropriate method, but to invoke a non-static method, you must have an instantiated object.
Summary of Java Reflection Mechanism learning