We know that an object has two types at run time, one is a compilation type and one is a run-time type. When a program runs, it is often necessary to discover real information about classes and objects. So how is this information obtained?
First, if we know the specifics of the type at compile and run time, we can manually convert an object to the runtime type.
Second, if we cannot predict at compile time what class the object and the class belong to, then the program only relies on the information of the runtime to discover the real information of the object and the class, then it must use the reflection technique.
before talking about specific launch techniques, I'd like to look back at some of the basic properties and principles related to the loading of classes to facilitate our better understanding of the role and characteristics of reflection. In fact, if a class can be executed, then for the JVM , its execution process is: class loading, connection, initialization. In this way, it is possible to get the class object of a class, that is , the java.lang.Class object, and on this basis gets the member variables of the class, methods and constructors and other intrinsic things.
So, what is the load of a class? Class is loaded by reading the class file into memory and creating a java.lang.Class object for it, which means that when the program uses any class, the system creates a The Java.lang.Class object. At the same time, class loading is done by the ClassLoader.
class: The connection phase is responsible for merging the class's binary data into the JRE. First, verify that the class being loaded has the correct internal structure; second, prepare to allocate memory for class variables of the class and set default initial values. Third, the parse replaces the symbolic reference in the binary data of the class with a direct reference. Initializes the class, primarily to initialize classes of variables.
In this way, we have a clear understanding of the life cycle of a class, and these also pave the way for our reflection mechanism, to get a class object that is threefold:
(1) Use forname (String clazzname) static method for class
(2) Call the Class property of A category to get the class object
(3) Call the GetClass () method of a class
with these three means, you can get a class of Class Object so that you can dynamically get the actual information for that object. Below is a concrete example of how to create an object of a class through a reflection mechanism, how to obtain the object's properties and methods, and dynamically inject new parameter values into the object.
1 Packagereflectionentity;2 Importjava.util.Date;3 4 /**5 * @authorxujiaqing6 * 7 */8 Public classStudent {9 //Get/set MethodTen PublicString Getstudentid () { One returnStudentID; A } - - Public voidSetstudentid (String studentid) { the This. StudentID =StudentID; - } - - PublicString Getstudentname () { + returnStudentname; - } + A Public voidsetstudentname (String studentname) { at This. Studentname =Studentname; - } - - PublicDate Getbirthday () { - returnbirthday; - } in - Public voidsetbirthday (Date birthday) { to This. Birthday =birthday; + } - the Public intGetscore () { * returnscore; $ }Panax Notoginseng - Public voidSetScore (intscore) { the This. score =score; + } A the PrivateString StudentID;//Student ID + PublicString Studentname;//Student Name - PrivateDate birthday;//Student Birthdays $ Private intScore;//Student Achievement $ //methods of implementing the task - Public voidAchievetask (String taskname) { -System.out.println (Studentname + "implemented" + TaskName + "technology"); the } -}
Packagereflectiontest;ImportJava.lang.reflect.Field;ImportJava.lang.reflect.Method;ImportJava.lang.reflect.Modifier;Importreflectionentity.student;/** * @authorxujiaqing **/ Public classTest { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub Try { //get the Class object for studentClass<?> clazz = Class.forName ("Reflectionentity.student"); //get all the properties in the classfield[] Fields =Clazz.getdeclaredfields (); //iterate through all the properties for(Field field:fields) {//Print property information, including access control modifiers, types, and property namesSystem.out.println (field); System.out.println ("Modifier:" +modifier.tostring (Field.getmodifiers ())); System.out.println ("Type:" +Field.gettype ()); System.out.println ("Property Name:" +field.getname ()); } //get all the methods in the classMethod[] Methods =Clazz.getdeclaredmethods (); for(Method method:methods) {//Print method SignatureSystem.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 methodclass<?>[] clazzes =method.getparametertypes (); for(class<?>class1:clazzes) {System.out.println ("Parameter type:" +Class1); } } //creating an instance from a class objectStudent Student =(Student) clazz.newinstance (); //Gets the Field object with the property name Studentname so that its value is reset belowField studentname = Clazz.getfield ("Studentname"); //set the value of Studentname to "xujiaqing"Studentname.set (student, "xujiaqing"); //get a Method object named "Finishtask" with the parameter type string by using the class objectMethod Finishtask = Clazz.getmethod ("Achievetask", String.class); //calling the Achievetask methodFinishtask.invoke (Student, "reflection"); } Catch(Exception e) {e.printstacktrace (); } }}
The directory structure and running result of the package are:
Class loading mechanism and reflection technology in Java