Java泛型、通配符、集合:编译错误
Java generics, wildcards, collections: compilation error
鉴于以下 class:
import java.util.ArrayList;
import java.util.Collection;
public class Main {
private static class A {
}
private static class B<T> {
private void thenReturn(T value) {
}
}
private static <T> B<T> when(T methodCall) {
return new B<T>();
}
private static Collection<? extends A> method() {
return new ArrayList<>();
}
public static void main(String[] args) {
Collection<? extends A> result = new ArrayList<>();
// Does not compile.
when(method()).thenReturn(result);
}
}
我收到编译错误The method thenReturn(Collection<capture#1-of ? extends Main.A>) in the type Main.B<Collection<capture#1-of ? extends Main.A>> is not applicable for the arguments (Collection<capture#3-of ? extends Main.A>)
我必须在 main 方法中更改什么才能编译?有没有比
更好的解决办法
public static void main(String[] args) {
Collection result = new ArrayList<>();
when(method()).thenReturn(result);
}
这可以解决这个问题 - 对于长表达式,捕获规则似乎有点紧张。
Collection<? extends A> result = new ArrayList<>();
B<Collection<? extends A>> when = when(method());
when.thenReturn(result);
鉴于以下 class:
import java.util.ArrayList;
import java.util.Collection;
public class Main {
private static class A {
}
private static class B<T> {
private void thenReturn(T value) {
}
}
private static <T> B<T> when(T methodCall) {
return new B<T>();
}
private static Collection<? extends A> method() {
return new ArrayList<>();
}
public static void main(String[] args) {
Collection<? extends A> result = new ArrayList<>();
// Does not compile.
when(method()).thenReturn(result);
}
}
我收到编译错误The method thenReturn(Collection<capture#1-of ? extends Main.A>) in the type Main.B<Collection<capture#1-of ? extends Main.A>> is not applicable for the arguments (Collection<capture#3-of ? extends Main.A>)
我必须在 main 方法中更改什么才能编译?有没有比
更好的解决办法 public static void main(String[] args) {
Collection result = new ArrayList<>();
when(method()).thenReturn(result);
}
这可以解决这个问题 - 对于长表达式,捕获规则似乎有点紧张。
Collection<? extends A> result = new ArrayList<>();
B<Collection<? extends A>> when = when(method());
when.thenReturn(result);