我们有一个或多或少像下面这样的方法。 但是我们现在返回列表 ,它在函数bla()中将在运行时返回List<Bar>
。从泛型函数返回泛型类型
我正在寻找一种方法,使双方
List<Interface> = troubleFuction(foo, bar.getCLass());;
和
List<Bar> = troubleFuction(foo, bar.getCLass());;
可能。 basicaly我希望它返回的是与接口兼容列表 然而,这提供了以下错误
*类型不匹配:不能从List<capture#3-of ? extends Bar>
转换为List<Interface>*
有没有什么办法让这个返回类型可能或不运行时擦除使这不可能
public <T1 extends Interface, T2 extends Interface> List<"problem"> troubleFunction(T1 in, Class<T2> clazz) {
return in.doStuffWhichGeneratesAlistOF(clazz)
}
public void bla() {
Foo foo = new Foo(); // implements interface
Bar bar = new Bar(); // implements interface
List<Interface> ifaces = toubleFuction(foo, bar.getCLass());
List<Bar> mustAlsoWork = toubleFuction(foo, bar.getCLass());
}
编辑: 在很多现有的代码库的方法被称为像
List<Bar> result = troubleFunction(List<Interface> list, Bar.class);
因此该返回类型必须保持兼容(重写/重因子不是一个选项)
基本上我想的方法,如果称为
troublefunction(foo, Bar.class);
和 List<? super Foo>
时返回列表<? super Bar>
叫做
troublefunction(foo, Bar.class);
在Java中,函数被称为方法。 – eleven81 2009-05-26 14:50:42
接口不是保留字? – 2009-05-26 14:56:19