为什么允许通过反射访问Java私有字段? [英] Why is it allowed to access Java private fields via reflection?

查看:191
本文介绍了为什么允许通过反射访问Java私有字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个例子:

import java.lang.reflect.Field;

public class Test {

    public static void main(String[] args) {
        C c = new C();
        try {
            Field f = C.class.getDeclaredField("a");
            f.setAccessible(true);
            Integer i = (Integer)f.get(c);
            System.out.println(i);
        } catch (Exception e) {}
    }
}

class C {
    private Integer a =6;
}

允许您通过反射访问类的私有字段似乎不合逻辑。为什么这样的功能可用?允许这样的访问是不是危险?

It seems illogical that you are allowed to access private fields of classes with reflection. Why is such a functionality available? Isn't it "dangerous" to allow such access?

推荐答案

私人旨在防止意外滥用,而不是作为安全机制。如果您选择绕过它,那么您可以自担风险并假设您知道自己在做什么。

Private is intended to prevent accidental misuse, not as a security mechanism. If you choose to bypass it then you can do so at your own risk and the assumption you know what you are doing.

这篇关于为什么允许通过反射访问Java私有字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆