Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".

like image 696
Mike Hedman Avatar asked Jan 14 '23 06:01

Mike Hedman


1 Answers

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 {
}
like image 73
Tom Hawtin - tackline Avatar answered Feb 02 '23 07:02

Tom Hawtin - tackline