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

前端 未结 14 1692
梦毁少年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 11:53

    You can use jOOR for that.

    class Foo {
        private final String value = "ABC";
    }
    class Bar {
        private final Foo foo = new Foo();
        public String value() {
            return org.joor.Reflect
                .on(this.foo)
                .field("value")
                .get();
        }
    }
    class BarTest {
        @Test
        void accessPrivateField() {
            Assertions.assertEquals(new Bar().value(), "ABC");
        }
    }
    

提交回复
热议问题