当它“嵌套在另一个通配符中”时,我正在努力捕获通配符.
可能吗?
代码:
public class ConvolutedGenerics {
// listClass is a class implementing a List of some Serializable type
public void doSomethingWithListOfSerializables(
Class extends List extends Serializable>> listClass) {
// Capture '? extends Serializable' as 'T extends Serializable'
// The line does not compile with javac 7
captureTheWildcard(listClass); //
}
// listClass is a class implementing a List of some Serializable type
private
void captureTheWildcard(
Class extends List* ? extends */T>> listClass) {
// Do something
}
}
用javac 7编译产生:
ConvolutedGenerics.java:18: error: method captureTheWildcard in class ConvolutedGenerics cannot be applied to given types;
captureTheWildcard(listClass);
^
required: Class extends List>
found: Class
reason: no instance(s) of type variable(s) T exist so that argument type Class conforms to formal parameter type Class extends List>
where T is a type-variable:
T extends Serializable declared in method captureTheWildcard(Class extends List>)
where CAP#1 is a fresh type-variable:
CAP#1 extends List extends Serializable> from capture of ? extends List extends Serializable>
1 error
除了我发现的更简单的案例之外
但我无法从那些推断出我的问题的答案.
最佳答案 你可能已经知道,这是不可能的.
让我用一个反例来说明:
List foo = Arrays.asList(1,2,3);
List bar = Arrays.asList("hi","mom");
List> baz = Arrays.asList(foo, bar);
doSomethingWithListOfSerializables(baz);
public void doSomethingWithListOfSerializables(
List extends List extends Serializable>> listList) {
captureTheWildcard(listList);
}
private
void captureTheWildcard(
List extends List> listList) {
// Do something
}
应该是什么?