Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

Java reflection - impact of setAccessible(true)

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?

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?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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):

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
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...