Java reflection - impact of setAccessible(true)

后端 未结 4 1255
萌比男神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:00

    import java.lang.reflect.Field;
    import java.lang.reflect.Method;
    
    public class PrivateVariableAcc {
    
        public static void main(String[] args) throws Exception {
            PrivateVarTest myClass = new PrivateVarTest();
            Field field1 = myClass.getClass().getDeclaredField("a");
            field1.setAccessible(true);
            System.out.println("This is access the private field-"
                + field1.get(myClass));
            Method mm = myClass.getClass().getDeclaredMethod("getA");
            mm.setAccessible(true);
            System.out.println("This is calling the private method-"
                + mm.invoke(myClass, null));
        }
    
    }
    

提交回复
热议问题