考虑以下(不可更改的)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"
正如代码注释中提到的,我在 Holder 类中调用 doFoo() 时遇到问题,因为当时不知道扩展 Foo
and 的确切类型实现 Bar
,所以我不能简单地将它转换为这样的类型。有没有办法在不改变 Holder
、Foo
和 Bar
界面的情况下解决这个问题?
最佳答案
您可以在私有(private)帮助器方法中调用doFoo
,该方法为强制转换引入正确的类型:
public void takeOverTheWorld() {
if(this.foo instanceof Bar)
doBarFoo();
}
private <T extends Foo & Bar> void doBarFoo() {
Foo.doFoo((T)this.foo);
}
如果您不介意该类型是公共(public)接口(interface)的一部分,您甚至可以在 takeOverTheWorld
中执行此操作:
public <T extends Foo & Bar> void takeOverTheWorld() {
if(this.foo instanceof Bar)
Foo.doFoo((T)this.foo);
}
关于java - 类型边界 : Propagate parameter with multiple bounds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32732203/