How to read the value of a private field from a different class in Java?

前端 未结 14 1707
梦毁少年i
梦毁少年i 2020-11-21 11:28

I have a poorly designed class in a 3rd-party JAR and I need to access one of its private fields. For example, why should I need to choose priv

相关标签:
14条回答
  • 2020-11-21 12:10

    In order to access private fields, you need to get them from the class's declared fields and then make them accessible:

    Field f = obj.getClass().getDeclaredField("stuffIWant"); //NoSuchFieldException
    f.setAccessible(true);
    Hashtable iWantThis = (Hashtable) f.get(obj); //IllegalAccessException
    

    EDIT: as has been commented by aperkins, both accessing the field, setting it as accessible and retrieving the value can throw Exceptions, although the only checked exceptions you need to be mindful of are commented above.

    The NoSuchFieldException would be thrown if you asked for a field by a name which did not correspond to a declared field.

    obj.getClass().getDeclaredField("misspelled"); //will throw NoSuchFieldException
    

    The IllegalAccessException would be thrown if the field was not accessible (for example, if it is private and has not been made accessible via missing out the f.setAccessible(true) line.

    The RuntimeExceptions which may be thrown are either SecurityExceptions (if the JVM's SecurityManager will not allow you to change a field's accessibility), or IllegalArgumentExceptions, if you try and access the field on an object not of the field's class's type:

    f.get("BOB"); //will throw IllegalArgumentException, as String is of the wrong type
    
    0 讨论(0)
  • 2020-11-21 12:10

    If using Spring, ReflectionTestUtils provides some handy tools that help out here with minimal effort. It's described as being "for use in unit and integration testing scenarios". There is also a similar class named ReflectionUtils but this is described as "Only intended for internal use" - see this answer for an interpretation of what this means.

    To address the posted example:

    Hashtable iWantThis = (Hashtable)ReflectionTestUtils.getField(obj, "stuffIWant");
    
    0 讨论(0)
提交回复
热议问题