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

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

    It is quite easy with the tool XrayInterface. Just define the missing getters/setters, e.g.

    interface BetterDesigned {
      Hashtable getStuffIWant(); //is mapped by convention to stuffIWant
    }
    

    and xray your poor designed project:

    IWasDesignedPoorly obj = new IWasDesignedPoorly();
    BetterDesigned better = ...;
    System.out.println(better.getStuffIWant());
    

    Internally this relies on reflection.

提交回复
热议问题