Search code examples
javaksoap2android-ksoap2wsdl2java

How to access method from two classes which do not share an interface?


I am creating a java library that will access web services, but the library will be called in different platforms, so we are using ksoap2 and ksoap2-android to generate helper classes for the different platforms. The problem is that we then have two sets of generated classes/methods whose signatures are equivalent, but which do not overtly share a Java Interface - so I can't figure a way to call them from my main code.

A simplified example:

//generated for Android
class A {
  public String sayHi() {
    return "Hi A";
  }
}

//generated for j2se
class B {
  public String sayHi() {
    return "Hi B";
  }
}

//main code - don't know how to do this
XXX talker = TalkerFactory.getInstance()
String greeting = talker.sayHi()

Of course, that last part is pseudo-code. Specifically, how can I call sayHi() on an instance of an object which I don't know the type of at compile time, and which does not conform to a specific interface? My hope is that there is some way to do this without hand editing all of the generated classes to add an "implements iTalker".


Solution

  • The straightforward way is to use an adapter.

    interface Hi {
        void sayHi();
    }
    
    public static Hi asHi(final A target) {
        return new Hi() { public void sayHi() { // More concise from Java SE 8...
            target.sayHi();
        }};
    }
    public static Hi asHi(final B target) {
        return new Hi() { public void sayHi() { // More concise from Java SE 8...
            target.sayHi();
        }};
    }
    

    In some circumstance it may be possible, but probably a bad idea and certainly less flexible, to subclass and add in the interface.

    public class HiA extends A implements Hi {
    }
    public class HiB extends B implements Hi {
    }