Java 反射 - setAccessible(true) 的影响 [英] Java reflection - impact of setAccessible(true)

查看:23
本文介绍了Java 反射 - setAccessible(true) 的影响的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一些注释来动态设置类中的字段值.因为无论是公共的、受保护的还是私有的,我都想这样做,所以每次在调用 set()setAccessible(true)> 方法.我的问题是 setAccessible() 调用对字段本身有什么样的影响?

I'm using some annotations to dynamically set values of fields in classes. Since I want to do this regardless of whether it's public, protected, or private, I am a calling setAccessible(true) on the Field object every time before calling the set() method. My question is what kind of impact does the setAccessible() call have on the field itself?

更具体地说,假设它是一个私有字段并且这组代码调用了setAccessible(true).如果代码中的其他地方通过反射检索相同的字段,该字段是否已经可以访问?还是 getDeclaredFields()getDeclaredField() 方法每次都返回 Field 对象的新实例?

More specifically, say it is a private field and this set of code calls setAccessible(true). If some other place in the code was then to retrieve the same field through reflection, would the field already be accessible? Or does the getDeclaredFields() and getDeclaredField() methods return new instances of a Field object each time?

我想另一种表述问题的方式是,如果我调用 setAccessible(true),完成后将其设置回原始值有多重要?

I guess another way of stating the question is if I call setAccessible(true), how important is it to set it back to the original value after I'm done?

推荐答案

使用 setAccessible() 你可以改变 AccessibleObject 的行为,即 Field 实例,但不是类的实际字段.这是文档(摘录):

With setAccessible() you change the behavior of the AccessibleObject, i.e. the Field instance, but not the actual field of the class. Here's the documentation (excerpt):

true 的值表示反射对象在使用时应取消对 Java 语言访问控制的检查

A value of true indicates that the reflected object should suppress checks for Java language access control when it is used

还有一个可运行的例子:

And a runnable example:

public class FieldAccessible {
    public static class MyClass {
        private String theField;
    }

    public static void main(String[] args) throws Exception {
        MyClass myClass = new MyClass();
        Field field1 = myClass.getClass().getDeclaredField("theField");
        field1.setAccessible(true);
        System.out.println(field1.get(myClass)); // no exception
        Field field2 = myClass.getClass().getDeclaredField("theField");
        System.out.println(field2.get(myClass)); // IllegalAccessException
    }

}

这篇关于Java 反射 - setAccessible(true) 的影响的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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