Java reflection_Simple example of changing 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; }}For example, change the value of name. How to change. How to change through java reflection
Let's first look at how to use reflection to call the getName method
class<DemoTest> calzz=DemoTest.class;Constructor cons=clazz.getConstructor(new class[]{});//This is the constructor to get the class object. The object of the class whose parameters are constructed. For example: DemoTest has a constructor method public DemoTest(String arg0,String arg1){......}
At this time, Constructor cons=clazz.getConstructor(new class[]{String.class,String.class}); the two String.cals correspond to arg0 and arg1 respectively.
Next is:
DemoTest test=(DemoTest)cons.newInstance(new Object[]{});// Generate the corresponding object. The parameter new Object[]{} is the specific value of the parameter corresponding to the construction method. As mentioned earlier: DemoTest test=(DemoTest)cons.newInstance(new Object[]{"Li Che","Zhang San"}); Next:
Method method=clazz.getMethod("getName",new Class[]{String.class}); method.invoke(test,new Object[]{"Wang Wu"});At this time, you can print out the Wu Wu.
Then how to change the value of name as private.
1. Get the 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 used. A value of false indicates that the reflected object should perform Java language access checking.
field.setAccessible(true);
3. Modify the variable value
field.set("name","Wang Wu");OK;
The same is true for accessing private methods.
Method method=clazz.getDeclaredMethod("getName2"); method.setAccessible(true); method.invoke(test,new Object[]{"Wang Wu"});Use getDeclaredFields to get private and public protected fields
If you use c.getFields(); you can only get properties of public type
The above java reflection_simple example of changing variables and methods in private is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.