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

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

问题描述

我正在使用一些注释来动态设置类中字段的值。因为无论是public,protected还是private,我都想这样做,每次调用<$ c之前,我都会在Field对象上调用 setAccessible(true) $ c> set()方法。我的问题是 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天全站免登陆