我无法理解通配符捕获错误,或找到绕过它的方法:
import java.util.List;
class A<B extends A.AA<? extends C>, C> {
List<C> list;
public void foo(B inner) {
C c = get();
inner.nop(c);
}
private C get() {
return list.get(0);
}
static public class AA<D> {
public void nop(D d) {
System.out.println(d);
}
}
}
这是javac输出:
Wildcards.java:10: error: method nop in class AA<D> cannot be applied to given types;
inner.nop(c);
^
required: CAP#1
found: C
reason: actual argument C cannot be converted to CAP#1 by method invocation conversion
where C,D are type-variables:
C extends Object declared in class A
D extends Object declared in class AA
where CAP#1 is a fresh type-variable:
CAP#1 extends C from capture of ? extends C
1 error
为什么我们不能将C的实例传递给B.nop()?
答案 0 :(得分:2)
假设您创建了A
的实例:
A<A.AA<String>,Object> a = new A<A.AA<String>,Object>();
A.AA<String> inner = new A.AA<String>();
a.foo(inner);
inner.nop()
应该预计String
,但您传递Object
。
一种可能的解决方法是:
class A<B extends A.AA<C>, C>