把一个方法或者变量声明成private,一定安全么?求解释。

解决方案 »

  1.   

    private 是安全的!前面有人说用反射可以读取,那是因为没有对 Java 进行安全策略文件的限制!
      

  2.   

    这在C++里通过破坏类的安全机制取得类地址就可以。但在java里没有指针,我想不出怎样不通过成员函数取得private成员的值的方法。请高手给个反例。另外,楼主,访问权限是为了帮助你管理好你的模块,如果你硬要访问,都设为public也未偿不可。
    规则的制定不是为了让你违反的。
      

  3.   

    反射:import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;@Retention(value = RetentionPolicy.RUNTIME)
    public @interface Value
    {
        String[] value();
    }public class Test01
    {
        //私有属性
        private int a = 0;    //私有方法
        @Value(value = { "hello", "world" })
        private int add(int b)
        {
            return a + b;
        }
    }
    import java.lang.annotation.Annotation;
    import java.lang.reflect.Field;
    import java.lang.reflect.Method;public class Test02
    {
        public static void main(String[] args) throws Exception
        {
            // Class cls = Test01.class; 或者
            Test01 tst = new Test01();
            Class cls = Class.forName("Test01");        // 反射设置属性
            Field field = cls.getDeclaredField("a");
            field.setAccessible(true);  //更改为可访问
            field.setInt(tst, 10);        // 反射调用方法
            Method method = cls.getDeclaredMethod("add", int.class);
            method.setAccessible(true);  //更改为可访问
            int rst = (Integer) method.invoke(tst, 8);
            System.out.println(rst);        // 反射取得方法的注解
            Annotation[] anns = method.getAnnotations();
            for (Annotation a : anns)
            {
                if (a instanceof Value)
                {
                    String[] strs = ((Value) a).value();
                    System.out.println(strs[0] + "$" + strs[1]);
                }
            }    }
    }