Java Reflection _ A simple example of changing the variables and methods in private
Class demotest{
private String name= "123";
Public GetName () {
System.out.println (' public getName ' + name);
return name;
Private GetName2 () {
System.out.println ("Private getName2" + name);
return name;
}
As this, change the value of name. How to change. How do I change through Java reflection
Let's take a look at how to invoke the GetName method with reflection.
Class<demotest> Calzz=demotest.class;
Constructor Cons=clazz.getconstructor (new class[]{});//This is the method of getting the class object to be constructed. parameter is an object of the class that constructs the parameter of the method.
For example, Demotest has a construction method that is public demotest (String arg0,string arg1) {...}
At this point, constructor Cons=clazz.getconstructor (new Class[]{string.class,string.class}), two string.calss correspond to ARG0,ARG1 respectively.
Next is:
Demotest test= (demotest) cons.newinstance (New object[]{});//generate the corresponding object. The parameter New object[]{} is the concrete value of the parameter corresponding to the constructor method. As just now:
demotest test= (demotest) cons.newinstance (new object[]{"Li Che", "John"});
Next:
Method Method=clazz.getmethod ("GetName", New Class[]{string.class});
Method.invoke (test,new object[]{"Harry"});
Then you can print out the King five.
How do you change the value of name as private?
1. Get field First,
Field Field=clazz.getdeclaredfield ("name");
2. Set the accessible flag of this object to the indicated Boolean value. A value of TRUE indicates that the reflected object should cancel the Java language access check when it is in use. A value of false indicates that the reflected object should implement the Java language access check.
Field.setaccessible (TRUE);
3. Modify the value of the variable
Field.set ("name", "Harry");
OK;
The same method is used to access private.
Method Method=clazz.getdeclaredmethod ("GetName2");
Method.setaccessible (true);
Method.invoke (test,new object[]{"Harry"});
You can get private and public protend protected fields with Getdeclaredfields.
If you use C.getfields (), you can only get properties of the public type
The above Java reflection _ change private variables and methods of a simple example is a small series to share all the content, hope to give you a reference, but also hope that we support cloud habitat community.