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

前端 未结 14 1726
梦毁少年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

    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");
    

提交回复
热议问题