Private类中有私用成员变量和私有方法,正常情况下外部类是无法访问私有方法和改变私有成员变量的值
public class Private {
private String names = "zs";
private String sayHello(String name){
return "say:"+name;
}
public String getNames(){
return names;
}
}
通过反射可实现对私有方法的访问和改变私有成员变量的值
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class TestPrivate01 {
public static void main(String[] args) throws Exception {
Private p = new Private();
//Private p2 = new Private();
//System.out.println(p.getClass()==p2.getClass());
Class<?> classType = p.getClass();
Method privatemethod = classType.getDeclaredMethod("sayHello", new Class[]{String.class});
Field field = classType.getDeclaredField("names");
//将访问权限控制检查压制(suppress)
privatemethod.setAccessible(true);
field.setAccessible(true);
field.set(p, "ls");
System.out.println(privatemethod.invoke(p, new Object[]{"Hello"}));
System.out.println(p.getNames());
}
}