【发布时间】:2015-09-23 14:34:53
【问题描述】:
考虑以下(不可更改的)API:
interface Bar {}
class Foo {
public static <T extends Foo & Bar> void doFoo(T param) {
System.out.println("I shall be your ruler");
}
}
现在我已经编写了一个接受通用Foo 的类,但如果该参数也是Bar,我想在某些方法中另外执行doFoo:
class Holder {
public Holder(Foo foo) {
this.foo = foo;
}
public void takeOverTheWorld() {
if(this.foo instanceof Bar) {
// Here I want to execute doFoo(), but I can't hand it over
// because the bounds don't match
// doFoo(this.foo);
)
// Enstablish my reign
}
}
Holder 的用法示例:
class Yes extends Foo implements Bar {
}
// ------
Holder h = new Holder(new Yes());
h.takeOverTheWorld(); // Should print "I shall be your ruler"
正如代码 cmets 中所述,我在 Holder 类中调用 doFoo() 时遇到问题,因为当时不知道扩展 Foo 和 实现 Bar 的确切类型,所以我不能简单地将它转换为这种类型。有没有办法在不改变Holder、Foo和Bar的接口的情况下解决这个问题?
【问题讨论】:
标签: java generics type-bounds