[英]Java generics, wildcards, collections: compilation error
Given the following 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);
}
}
I get the compilation error 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>)
我收到编译错误
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>)
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>)
What have I to change in the main method in order that it will compile? 为了对其进行编译,我需要对main方法进行哪些更改? Is there a better solution than
有没有比这更好的解决方案
public static void main(String[] args) {
Collection result = new ArrayList<>();
when(method()).thenReturn(result);
}
This works to get around it - it looks like the capture rules get a bit stretched for long expressions. 可以解决这个问题-看起来捕获规则对于长表达式而言有些延伸。
Collection<? extends A> result = new ArrayList<>();
B<Collection<? extends A>> when = when(method());
when.thenReturn(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.