Java reflection - impact of setAccessible(true)

后端 未结 4 1263
萌比男神i
萌比男神i 2020-11-28 23:43

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

4条回答
  •  生来不讨喜
    2020-11-29 00:04

    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
        }
    
    }
    

提交回复
热议问题