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

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

    You can use Manifold's @JailBreak for direct, type-safe Java reflection:

    @JailBreak Foo foo = new Foo();
    foo.stuffIWant = "123;
    
    public class Foo {
        private String stuffIWant;
    }
    

    @JailBreak unlocks the foo local variable in the compiler for direct access to all the members in Foo's hierarchy.

    Similarly you can use the jailbreak() extension method for one-off use:

    foo.jailbreak().stuffIWant = "123";
    

    Through the jailbreak() method you can access any member in Foo's hierarchy.

    In both cases the compiler resolves the field access for you type-safely, as if a public field, while Manifold generates efficient reflection code for you under the hood.

    Discover more about Manifold.

提交回复
热议问题