How to 'wrap' two classes with identical methods?

前端 未结 6 947
误落风尘
误落风尘 2021-02-15 10:52

I have to handle two classes with identical methods but they don\'t implement the same interface, nor do they extend the same superclass. I\'m not able / not allowed to change t

6条回答
  •  孤独总比滥情好
    2021-02-15 11:33

    There, a duck-typed solution. This will accept any object with valueOne, valueTwo properties and is trivially extensible to further props.

    public class Wrapper
    {
      private final Object wrapped;
      private final Map methods = new HashMap();
      public Wrapper(Object w) {
        wrapped = w;
        try {
          final Class c = w.getClass();
          for (String propName : new String[] { "ValueOne", "ValueTwo" }) {
            final String getter = "get" + propName, setter = "set" + propName;
            methods.put(getter, c.getMethod(getter));
            methods.put(setter, c.getMethod(setter, String.class));
          }
        } catch (Exception e) { throw new RuntimeException(e); }
      }
      public String getValueOne() {
        try { return (String)methods.get("getValueOne").invoke(wrapped); }
        catch (Exception e) { throw new RuntimeException(e); }
      }
      public void setValueOne(String v) {
        try { methods.get("setValueOne").invoke(wrapped, v); }
        catch (Exception e) { throw new RuntimeException(e); }
      }
      public String getValueTwo() {
        try { return (String)methods.get("getValueTwo").invoke(wrapped); }
        catch (Exception e) { throw new RuntimeException(e); }
      }
      public void setValueTwo(String v) {
        try { methods.get("setValueTwo").invoke(wrapped, v); }
        catch (Exception e) { throw new RuntimeException(e); }
      }
    }
    

提交回复
热议问题