这是我为了简化我的真实代码而编造的一个例子,所以如果它有点做作,我深表歉意。我想做的是从单个嵌套类型参数中有效地获取两个类型参数。我很确定这是不可能的,但我想我会试一试。
//Not legal java code
public class Foo<C extends Collection<T>> { //where T is another type parameter
private C coll;
public Foo(C coll) {
this.coll = coll;
}
public void add(T elem){
this.coll.add(elem);
}
//UPDATED TO ADD GETTER
/**
* I may need to retrieve the collection again, or pass it
* on to another function that needs the specific C type
*/
public C getColl(){
return coll;
}
}
...
List<String> strings = new ArrayList<String>();
Foo<List<String>> foo = new Foo<List<String>>(strings);
foo.add("hello");
我知道我可以通过添加另一个类型参数来做到这一点:
public class Foo<C extends Collection<T>,T>
但后来我必须添加多余的:
Foo<List<String>,String> foo = new Foo<List<String>,String>(strings);
在我的真实案例中,我的泛型有时可以在 implements 子句中指定,例如
public class Bar implements Baz<String>
那时必须指定第二个类型参数更加痛苦,因为感觉就像它把实现细节扔到了我的脸上。不得不说
Foo<Bar,String>
当 String 和 Bar 之间已经存在关系时,它看起来并不优雅。我知道它是 Java,所以这与领土有关,但只是好奇是否有解决方案。