标签:
//调用私有方法
package com.java.test; public class PrivateMethod { private String sayHello(String name) { return "hello "+name; } }
测试:
package com.java.test; import java.lang.reflect.Method; public class PrivateMethodTest { public static void main(String[] args)throws Exception { PrivateMethod p = new PrivateMethod(); Class<?> classType = p.getClass(); Method method = classType.getDeclaredMethod("sayHello", new Class[]{String.class}); method.setAccessible(true);//压制java的检查机制 String str = (String)method.invoke(p, new Object[]{"lzyer"}); System.out.println(str); } }
修改私有属性:
package com.java.test; public class PrivateField { private String name="zhangsan"; public String getName() { return this.name; } }
测试:
package com.java.test; import java.lang.reflect.Field; public class PrivateFieldTest { public static void main(String[] args)throws Exception { PrivateField p = new PrivateField(); Class<?> clazz = p.getClass(); Field field = clazz.getDeclaredField("name"); field.setAccessible(true);//压制java检查机制 field.set(p, "lisi"); System.out.println(p.getName()); } }
标签:
原文地址:http://www.cnblogs.com/lzeffort/p/4890736.html