The concept of Java reflection
Java reflection mechanism is in the running state, for any class , can know all the properties and methods of this class, for any one object , can call any of its methods and properties ; This dynamic acquisition of information and the ability to dynamically invoke the object's methods is called the reflection mechanism of the Java language
The Java reflection mechanism mainly provides the following purposes:
1. Determine the class to which any object belongs at run time
2. Constructing an object of any class at run time
3. Determine the member variables and methods that any one class has at run time
4. Methods for invoking any object at run time
Let's look at a simple example to understand how the reflection mechanism works in Java.
ImportJava.lang.reflect.Method;/*** Java reflection exercises. * * @authorWANGGC*/ Public classFornametest {/*** Entry function. * * @paramargs * Parameters *@throwsException * error message*/ Public Static voidMain (string[] args)throwsException {//Get classClass<?> cls = Class.forName (args[0]); //method of obtaining the corresponding object through classMethod[] Methods =Cls.getmethods (); //output each method name for(method Method:methods) {System.out.println (method); } }}
code examples such as the following
Using the reflection mechanism of Java, it is generally necessary to follow three steps:
1. Get the class object you want to manipulate
2. Use the class object obtained from the first step to get the method or property name of the Operation class
3. The method or property obtained by the second step of the operation
When Java runs, a class, regardless of how many objects are generated, will correspond to the same class object, which represents the classes and interfaces in the program that are running. There are three ways to get the class object for the action classes:
1. Call class's static method Forname, as in the above example;
2. Use the class's. class syntax, such as:class<?> cls = String.class;
3. Call the object's GetClass method, such as: String str = "ABC";class<?> CLS = str. getclass ();
Here's an example of how to execute a method of an object through the three steps you've previously complained about:
3ImportJava.lang.reflect.Method;4 5/**6 * Java reflection exercise. 7 * 8 *@authorWANGGC 9*/10 Public classReflectiontest {11 Public Static voidMain (string[] args)throwsException {display =NewDisPlay ();13//Get classClass<?> CLS =Display.getclass ();15//get the Show method of display class through classmethod = Cls.getmethod ("Show", String.class);17//call the Show methodMethod.invoke (DisPlay, "WANGGC");19 }20 }21 22classDisPlay {23 Public voidShow (String name) {System.out.println ("Hello:" +name);25 }26}
code examples such as the following
The previous example describes how to invoke a method of a class through reflection, and then an instance that tells you how to assign a value by reflection to a property of a class:
3ImportJava.lang.reflect.Field; 4 5/**6 * Properties of Java reflection practice. 7 * 8 *@authorWANGGC 9*/10 Public classReflectiontest {11 Public Static voidMain (string[] args)throwsException {12//set up student objectsStudent Student =NewStudent ();14//assigning values to student objectsStudent.setstuname ("WANGGC"); Student.setstuage (24); 17//creating a Copy target objectStudent deststudent =NewStudent ();19//Copy Student Objects20Copybean (student, deststudent);21st//Output Copy ResultsSystem.out.println (Deststudent.getstuname () + ":" 23 +deststudent.getstuage ()); 24 } 25 26/**27 * Copy Student object information. * *@paramFrom 30 * Copy Source Object *@paramdest 32 * Copy target object *@throwsException 34 * Exception*/36Private Static voidCopybean (object from, Object dest)throwsException {37//gets the class object of the copy source objectClass<?> Fromclass =From.getclass ();39//gets the list of properties of the copy source objectfield[] Fromfields =fromclass.getdeclaredfields ();41//gets the class object that copies the target objectClass<?> Destclass =Dest.getclass ();Destfield Field =NULL; 44 for(Field fromfield:fromfields) {45//gets the property name of the copy source objectString name =fromfield.getname ();47//gets the property that copies the same name of the target objectDestfield =Destclass.getdeclaredfield (name);49//to set the accessibility of a propertyFromfield.setaccessible (true); Wuyi Destfield.setaccessible (true); 52//assigns the value of the property of the copy source object to the corresponding property of the copy target object53Destfield.set (dest, Fromfield.get (from));54 } 55 } 56 } 57 58/**59 * Student class. -*/61classStudent {62/**name*/63PrivateString Stuname;64/**Age*/65Private intStuage;66 67/**68 * Get the student's name. * *@returnStudent Name*/72 PublicString Getstuname () {73returnStuname;74 } 75 76/**77 * Set student name * *@paramStuname 80 * Student name Bayi*/82 Public voidsetstuname (String stuname) {83 This. Stuname =Stuname;84 } 85 86/**87 * Get student Age * *@returnStudent Age*/91 Public intGetstuage () {92returnStuage;93 } 94 95/**96 * Set Student Age * 98 *@paramstuage 99 * Student Age*/101 Public voidSetstuage (intstuage) {102 This. Stuage =Stuage;103 }104}
code examples such as the following
The previous section describes how to manipulate the methods and properties of a class with the Java reflection mechanism, and then an example that describes how to create an object of a class at run time:
3ImportJava.lang.reflect.Field;4 5/**6 * Properties of Java reflection practice. 7 * 8 *@authorWANGGC 9*/10 Public classReflectiontest {11 Public Static voidMain (string[] args)throwsException {12//set up student objectsStudent Student =NewStudent ();14//assigning values to student objectsStudent.setstuname ("WANGGC");Student.setstuage (24);17//creating a Copy target objectStudent deststudent =(Student) Copybean (Student);19//Output Copy ResultsSystem.out.println (Deststudent.getstuname () + ":" 21 +deststudent.getstuage ());22 }23 24/**25 * Copy student object information. * *@paramfrom28 * Copy source Object *@paramDest30 * Copy target object *@throwsException32 * Exception*/34Private StaticObject Copybean (object from)throwsException {35//gets the class object of the copy source objectClass<?> Fromclass =From.getclass ();37//gets the list of properties of the copy source objectfield[] Fromfields =fromclass.getdeclaredfields ();39//gets the class object that copies the target objectINTs Object =fromclass.newinstance ();41 for(Field fromfield:fromfields) {42//to set the accessibility of a propertyFromfield.setaccessible (true);44//assigns the value of the property of the copy source object to the corresponding property of the copy target object45Fromfield.set (INTs, Fromfield.get (from));46 }47 48returnints;49 }50 }51 52/**53 * Student class. Wu*/55classStudent {56/**name*/57PrivateString Stuname;58/**Age*/59Private intStuage;60 61/**62 * Get the student's name. * *@returnStudent Name*/66 PublicString Getstuname () {67returnStuname;68 }69 70/**71 * Set student name * *@paramstuName74 * Student name*/76 Public voidsetstuname (String stuname) {77 This. Stuname =Stuname;78 }79 80/**81 * Access to Student age * *@returnStudent Age*/85 Public intGetstuage () {86returnStuage;87 }88 89/**90 * Set student age * *@paramstuAge93 * Student Age 94*/95 Public voidSetstuage (intstuage) {96 This. Stuage =Stuage;97 }98}
code examples such as the following
Add: There are two methods for getxxx and getgetdeclaredxxx when obtaining methods, properties, and constructors for a class. The difference is that the former returns methods and properties that have access to public, including those in the parent class, but the latter returns the methods and properties of all access rights, not including the parent class's
The reflection mechanism in Java