Is it possible to invoke private attributes or methods via reflection

前端 未结 3 1062
甜味超标
甜味超标 2020-12-24 10:44

I was trying to fetch the value of an static private attribute via reflection, but it fails with an error.

Class class = home.Student.class;
Field field = st         


        
相关标签:
3条回答
  • 2020-12-24 11:14

    Yes, you can "cheat" like this:

        Field somePrivateField = SomeClass.class.getDeclaredField("somePrivateFieldName");
        somePrivateField.setAccessible(true); // Subvert the declared "private" visibility
        Object fieldValue = somePrivateField.get(someInstance);
    
    0 讨论(0)
  • 2020-12-24 11:20

    You can set the field accessible:

    field.setAccessible(true);
    
    0 讨论(0)
  • 2020-12-24 11:31

    Yes it is. You have to set them accessible using setAccessible(true) defined in AccesibleObject that is a super class of both Field and Method

    With the static field you should be able to do:

    Class class = home.Student.class;
    Field field = studentClass.getDeclaredField("nstance");
    field.setAccessible(true); // suppress Java access checking
    Object obj = field.get(null); // as the field is a static field  
                                  // the instance parameter is ignored 
                                  // and may be null. 
    field.setAccesible(false); // continue to use Java access checking
    

    And with the private method

    Method method = studentClass.getMethod("addMarks");
    method.setAccessible(true); // exactly the same as with the field
    method.invoke(studentClass.newInstance(), 1);
    

    And with a private constructor:

    Constructor constructor = studentClass.getDeclaredConstructor(param, types);
    constructor.setAccessible(true);
    constructor.newInstance(param, values);
    
    0 讨论(0)
提交回复
热议问题