简体   繁体   中英

How to give two different classes the same interface?

Can I give 2 different classes (that I cannot modify as they are autocreated webservice classes) the same interface?

Problem: I have several autocreated webservice classes, that have a method with the same signature. But as the classes have no common interface, I cannot group them and thus cannot call both of them from a single method.

Example:

class A {
  void sameMethod();
}
class B {
  void sameMethod();
}


class MyService() {
  //I cannot do the following as I cannot group A and B with the same interface
  void callAorB(<Class A or B> object) {
     object.sameMethod();
  }
}

Will it still be somehow possible to just execute òbject.sameMethod() even though I cannot make a common reference between class A and class B`?

If you can't modify the classes then no, you can't force the interfaces onto the objects. You can however create an interface and two adapters which implement this interface.

The hacked solution would be:

if(object instanceof A)
   ((A)object).sameMethod();
else if(object instanceof B)
   ((B)object).sameMethod();

but if you can make them implement an interface would be much better

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM