First, each class generates a. class file when it is instantiated. The class object creates a class object for the. class file when it is read into memory.
Reflection is the manipulation of a class object.
1 PackageReflect.vo;2 3 /**4 * @authorGuohao5 * Java Test class student6 */7 Public classStudent {8 PrivateString name;9 Private intAge ;Ten Private floatscore; One A PublicStudent () { - } - the PublicString GetName () { - returnname; - } - + Public voidsetName (String name) { - This. Name =name; + } A at Public intGetage () { - returnAge ; - } - - Public voidSetage (intAge ) { - This. Age =Age ; in } - to Public floatGetscore () { + returnscore; - } the * Public voidSetScore (floatscore) { $ This. score =score;Panax Notoginseng } - the}
The 1.Object class provides a way to return a class class object GetClass ()
1 PackageReflect.vo;2 Public classTest {3 4 Public Static voidMain (string[] args)throwsException {5 6Student stu =NewStudent ();//This new creates a student object, a class object. 7Class cls = Stu.getclass ();//Get Class object8 System.out.println (Cls.getname ()); 9 Ten}
2. Take advantage of "class. Class" To obtain
1 PackageReflect.vo;2 3 Public classTest {4 5 Public Static voidMain (string[] args)throwsException {6Class cls = Student.class; 7 System.out.println (CLS);8 }9}
3. Use the static method of class to obtain Class.forName ();
1 PackageReflect.vo;2 3 Public classTest {4 5 Public Static voidMain (string[] args)throwsException {6Class<?> cls = Class.forName ("Reflect.vo.Student");7 System.out.println (CLS);9 }Ten}
Three ways to use the third, the first object has to reflect what to do.
The second type of package that needs to be imported is too strong to throw a compile error without a packet.
Generally the third type, a string can be passed in also can be written in the configuration file medium multiple methods.
Note: The last sentence is quoted from 71799078
Java reflection to produce instantiated objects of class three methods