通过反射可以访问私有变量、方法
今天学习RTTI的时候,发现通过反射可以访问私有方法、也可以改变私有变量的值,这样来说的话private 是不是基本没有意义了啊?!
public class TestMain { public static Object acessPrivateMethod(Object o,String methodName) throws Exception{ /*获得所有的方法 Method []Methods=o.getClass().getDeclaredMethods(); for (Method method : Methods) { System.out.println(method.getName()); } */ //获得所有属性名字 Field []fields=o.getClass().getDeclaredFields(); for (Field f : fields) { System.out.println(f.getName()); if(f.getName().equals("age")){ f.setAccessible(true); f.set(o, 24);//改变私有变量age的值 System.out.println(f.get(o)); } } Method m=o.getClass().getDeclaredMethod(methodName); m.setAccessible(true); return m.invoke(o); } public static void main(String[]args) throws Exception{ User u=User.class.newInstance(); String sex=u.getSex(); System.out.println("性别:"+sex); System.err.println("使用反射访问私有方法:"); String s=(String) acessPrivateMethod(u,"getName"); System.out.println("名字:"+s); }}