首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

透过反射可以访问私有变量、方法

2012-10-30 
通过反射可以访问私有变量、方法今天学习RTTI的时候,发现通过反射可以访问私有方法、也可以改变私有变量的值

通过反射可以访问私有变量、方法
今天学习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);    }}

热点排行