Run-time
Determine the class to which any one object belongs
Constructs an object of any one class
Determine the member variables and methods that any one class has
Method that invokes an object
Note point: Runtime, not compile time
First of all, the concept of things, small series will not elaborate, want to understand the direct ask Niang bar, directly on dry.
Specific steps to make a method call by reflection:
1. first to obtain the Class object (means more, for example through forname means and invoketester.class means)
2. If you want to invoke methods to get The Method object (), get the field[] object if you want to manipulate the field
The above two points for a moment in the following code will be reflected in, we do not worry.
Small series here want to say two, about the invocation of the implementation of the class construction method, of course, the construction method is divided into parameters and without parameters, first a period without parameters
Class C = test.class;c.newinstance ();
another way to do this:
Constructor con = c.getconstructor (new class[]{}); Con.newinstance (new object[]{});
constructed method call with parameters
Class C = test.class; Constructor con = c.getconstructor (new Class[]{double.class,int.class}); Con.newinstance (New object[]{1.2,3})//Type consistent
declared again. Reflection is the basis of the big frame, through reflection we can get the class, the method of the class, the variables of the class and so on, so that the present struts,spring and so on.
Finally look at a piece of code:
Package Cn.tgb.reflection;public class Privatetest {private string name = "Hello";p ublic String getName () {return This.nam e;}}
Q: What if the value of the variable name is changed to world?
Of course, by the way of reflection, look at the next piece of code.
Package Cn.tgb.reflection;import Java.lang.reflect.field;public class Reflectiontest {public static void main (string[] args) throws Exception {privatetest pt = new Privatetest (); class<?> clazz = Privatetest.class; Field field = Clazz.getdeclaredfield ("name"); Field.setaccessible (true);//suppress access control checks for Java. Field.set (PT, "World"); System.out.println (Field.get (PT));}}
You can run the above code to see if the output structure is world. Finally, by reflection, you get the name of the field in the class, and you can modify the name of the field by using the Set method.