使用实现多个泛型接口的参数 [英] Using parameter that implements multiple interfaces pre-generics

查看:551
本文介绍了使用实现多个泛型接口的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我具有以下接口:

public interface I1 {
  void foo();
}

public interface I2 {
  void bar();
}

和类:

public class A extends AParent implements I1, I2 {
   // code for foo and bar methods here
}

public class B extends BParent implements I1, I2 {
  // code for foo and bar methods here
}

public class C extends CParent implements I1 {
  // code for foo method here
}

现在,有了泛型,我可以有一个像这样的方法:

Now, with generics I can have a method like:

public <T extends I1 & I2> void method(T param) {
  param.foo();
  param.bar();
}

我可以使用A和B作为参数来调用它,但是不能使用C(它不实现I2)来调用它.

and I can call it with both A and B as parameters, but not with C (it doesn't implement I2).

是否有一种方法可以实现这种类型的安全类型泛型(java< 1.5).

Was there a way of achieving this type of type safety pre generics (java < 1.5).

请考虑A,B和C具有不同的继承树,并且做诸如AParent和BParent之类的具有共同父代的事情并不是真正的选择.

Consider that A, B and C have different inheritance trees, and it's not really an option to do something like AParent and BParent having a common parent themselves.

我知道您可以做到:

public void method(I1 param) {
  param.foo();
  ((I2)param).bar();
}

但是您还可以调用未实现I2的method(new C()),因此会遇到麻烦.

but then you could also call method(new C()) which doesn't implement I2, so you get into trouble.

那么您还有其他方法可以做到这一点吗?

So are there any other ways you could have done this?

P.S. :我真的不需要这样做,主要是出于好奇.

P.S. : I don't really need to do this, it's mostly out of curiosity that I ask.

推荐答案

创建第三个接口I3扩展了I1和I2.然后,类A和B都实现I3,并且通用方法接受I3.

Create a third interface I3 extends I1 and I2. Then class A and B both implement I3, and the generic method accepts I3.

那也许是唯一的方法.

这篇关于使用实现多个泛型接口的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆