简体   繁体   English

如何给两个不同的类相同的接口?

[英]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? 我可以给2个不同的类(我不能修改,因为它们是自动处理的webservice类)相同的接口?

Problem: I have several autocreated webservice classes, that have a method with the same signature. 问题:我有几个自动处理的webservice类,它们有一个具有相同签名的方法。 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`? even though I cannot make a common reference between A类andeven though I cannot make a common reference between它仍然可能以某种方式执行òbject.sameMethod()吗?

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 但如果你能让他们实现一个接口会好得多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何注入实现同一接口的两个不同类的两个实例? - How to inject two instances of two different classes which implement the same interface? 如何在两个不同的类中使用相同的计数器 - How to use the same counter in two different classes 如何在仅使用批注实现相同接口的不同类中使用@autowired - How to use @autowired in different classes that implement the same interface with only annotations 如何实例化(在方法内部)实现同一接口的不同类? - How to instantiate (inside a method) different classes that implement the same interface? 如何分离实现相同接口的两个类的函数模拟? - How to separate function mocks of two classes that implement the same interface? 如何为实现相同接口的两个类制作双向适配器? - How to make bidirectional adapter for two classes that implement the same interface? 如何在Swig中使用相同的接口生成两个代理类 - How to generate two proxy classes using the same interface in swig 在Java中查找资源时,两个类在相同的代码上提供不同的输出 - Two classes give the output different on same code while locating a resource in java 不同类中的两个相同变量 - Two of the same variables in different classes 使用不同类型参数实现接口的两个类 - Two classes implementing interface with different type arguments
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM