The so-called reflection, in the runtime state, gets the properties and methods in the class, as well as a mechanism for invoking the methods Therein. The purpose of this mechanism is to obtain the classes (class) and the properties (Field), methods, and methods in which the runtime knows, as well as to set the property values in Them. The most important step in implementing reflection in java, and the first step is to get the class object, which allows you to call the appropriate method to get the properties, methods, and methods in the class from that Object. There are several implementations of reflection in Java: 1. You can get the class object represented by the string by loading the string with the Class.forName () method. For example:class<?> clazz = Class.forName ("java.lang.String") You can get the class object of the String class. It is worth noting that the string must be the full name of the class, that is, the package name + class Name. The code below is the configuration of an action in the Struts configuration file Struts.xml.
<action name= "registe" class= "cn.com.huixin.struts2.RegisteAction" > <result>/registeresult.jsp</ result> <result name= "input" >/registe2.jsp</result></action>
The Class property here gives a string of the full name of a class, and how does the server get the class object from this string? is to registeaction objects through the reflection Mechanism. Then call the default Execute () method in this class. 2. The class object is obtained by calling the classes property through the name For example:class<?> Clazz = String.class can also get the class object of the String class. 3. Call the GetClass () method of the Instance. For example: Date date = new Date ();
Class<?> clazz = Date.getclass (); The class object of the date instance can be obtained by two lines of code Above. 4. If the wrapper class is a basic type, you can get the class object of the wrapper class by calling the wrapper Class's type Property.
For example:class<?> Clazz = integer.type; Below is a piece of code that shows how to implement a reflection Mechanism.
Package cn.com.huixin.blogcode;
Import java.util.Date;
public class Student {private string studentid; public string studentname; private Date birthday; private int score; Public String Getstudentid () {return studentid;} public void Setstudentid (String studentid) {this.studentid = studentid;} Public String getstudentname () {return studentname;} public void Setstudentname (String Studentname) {this.studentname = studentname;} Public Date getbirthday () {return birthday;} public void Setbirthday (Date birthday) {this.birthday = birthday;} public int Getscore () {return score;} public void SetScore (int score) {this.score = score;} public void Finishtask (String Taskname) {System.out.println (studentname + "completed" + taskname + "job");}}
In the Reflectiontest class below, the reflection mechanism is used to get the properties and methods in the student class, and an instance is generated to invoke the Finishtask Method.
Package cn.com.huixin.blogcode;
Import Java.lang.reflect.field;import Java.lang.reflect.method;import java.lang.reflect.Modifier;
public class Reflectiontest {
public static void main (string[] Args) {try {//get student Class object class<?> clazz = Class.forName ("cn.com.huixi N.blogcode.student "); Get all the properties in the class field[] fields = Clazz.getdeclaredfields (); Traverse all properties for (field Field:fields) {///print attribute information, including access control modifier, type and attribute name System.out.println (field);
system.out.println ("modifier:" + modifier.tostring (field.getmodifiers ())); system.out.println ("type:" + field.gettype ()); system.out.println ("property name:" + Field.getname ()); } //gets All methods in the class method[] methods = Clazz.getdeclaredmethods (); for (method method:methods) { //printing method signature system.out.println (method); System.out.println ("modifier:" + modifier.tostring (method.getmodifiers ())); system.out.println ("method name:" + method.getname ()); system.out.println ("return type:" + method.getreturntype ()); //gets the Parameter object of the method class<?>[] clazzes = Method.getparametertypes (); for (class<?> class1:clazzes) { system.out.println ("parameter type:" + class1); } } //creates an instance from a class object student Student = (Student) clazz.newinstance (); //gets The Field object whose property is named Studentname so that its value is reset below Field studentname = Clazz.getfield ("studentname"), //setting studentname value is "zhang san" Studentname.set (student, "zhang san"); //a method with a class object named "finishtask" with a parameter type of string ( METHOD) object method finishtask = Clazz.getmethod ("finishtask", string.class); // Call the Finishtask method finishtask.invoke (student, "math"); } catch (Exception e) { e.printstacktrace (); } }
}
Class<?> clazz = Class.forName ("cn.com.huixin.blogcode.Student") obtains the Student Class object through the first method described Above. The string here must be the full path name of the class, the package name + class Name. of course, the Student class object can also be obtained from the second or third method described Above. For example:
(1), call the Class property of the student
Class<?> clazz = student.class;
(2), Call the GetClass () method of the student instance
Student stu = new Student ();
Class<?> clazz = Stu.getclass ();
Whichever method you use to get the class object, you get the class object, and the action method is the Same.
field[] fields = Clazz.getdeclaredfields () Gets the properties defined in the class, including the private property, but does not include attributes inherited from the parent class.
The For loop down iterates through the field array fields. Field.getmodifiers () Gets the modifier for the property, which returns an integer number, so the integer is converted to a string using the modifier.tostring () method.
method[] methods = Clazz.getdeclaredmethods () Gets the methods in the class, including the private method, but does not include the method inherited from the parent class.
Down the Traversal method array methods. Method.getreturntype () Gets the return type of the Method. Method.getparametertypes () Gets the parameter type of the method, because the method may have more than one parameter, so the return value is a class array.
Student Student = (Student) clazz.newinstance () Creates an instance of Newinstance by invoking the Student () method of the class Object. The Newinstance () method actually calls the default parameterless construction Method.
Field studentname = Clazz.getfield ("studentname") Gets the attribute in the class named "studentname", it should be noted that the GetField () method can only get the properties of public in the class. So "studentname" in the student class is set to Public.
Studentname.set (student, "zhang San") Sets the Studentname property value in the student instance to "zhang san".
Method Finishtask = Clazz.getmethod ("finishtask", String.class) obtains a method object named "finishtask" in the class and has a String type Parameter.
Finishtask.invoke (student, "math") invokes the Finishtask method in the instance student, and passes in a parameter.
The result of the execution is:
Private java.lang.String Cn.com.huixin.blogcode.Student.studentID Modifier: private Type: class Java.lang.String Property Name: Studentidpublic java.lang.String Cn.com.huixin.blogcode.Student.studentName modifier: Public type: Class Java.lang.String property Name: studentnameprivate Java.util.Date cn.com.huixin.blogcode.Student.birthday modifier: Private Type: Class Java.util.Date property name: birthdayprivate int Cn.com.huixin.blogcode.Student.score modifier: Private Type: int property name: scorepublic void Cn.com.huixin.blogcode.Student.finishTask (java.lang.String) modifier: Public method name: finishtask return type: void parameter Type: class Java.lang.Stringpublic java.lang.String Cn.com.huixin.blogcode.Student.getStudentID () Modifier: Public method Name: Getstudentid return type: class java.lang.Stringpublic void Cn.com.huixin.blogcode.Student.setStudentID ( Java.lang.String) modifier: Public method name: Setstudentid return type: void parameter Type: class Java.lang.Stringpublic java.lang.String Cn.com.huixin.blogcode.Student.getStudentName () modifier: Public method name: Getstudentname return type: class Java.lang.Stringpublic void Cn.com.huixin.blogcode.Student.setStudentName (java.lang.String) Modifier: public method name: setstudentname return type: void parameter Type: class Java.lang.Stringpublic java.util.Date Cn.com.huixin.blogcode.Student.getBirthday () modifier: Public method name: Getbirthday return type: class Java.util.Datepublic void Cn.com.huixin.blogcode.Student.setBirthday (java.util.Date) modifier: Public method name: setbirthday return type: void parameter Type: class java.util.Datepublic int Cn.com.huixin.blogcode.Student.getScore () modifier: public method name: Getscore return type: intpublic void Cn.com.huixin.blogcode.Student.setScore (int) modifier: Public method name: SetScore return type: void parameter type: int Zhang San completed math job
How reflection is implemented in Java