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

I am creating a java library that will access web services, but the library will be called on different platforms, so we use ksoap2 and ksoap2-android to create helper classes for different platforms. The problem is that we then have two sets of generated classes / methods whose signatures are equivalent, but which do not explicitly share the Java interface, so I cannot figure out how 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, this last part is pseudo code. In particular, how can I call sayHi () on an instance of an object that I don't know type at compile time and that does not match a specific interface? I hope there is a way to do this without manually editing all the generated classes to add "implements iTalker".

+4
source share
1 answer

An easy 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 cases this may be possible, but probably a bad idea and, of course, less flexible for subclassing and adding to the interface.

 public class HiA extends A implements Hi { } public class HiB extends B implements Hi { } 
+9
source

Source: https://habr.com/ru/post/1483654/


All Articles