public class Foo<T> {
public static <T> Foo<T> newFoo() {
return new Foo<>();
}
public Bar<T, T> toBar() {
return new Bar<>(this, new ArrayList<T>());
}
}
public class Bar<S, T> {
public Bar(Foo<T> Foo, List<S> list) {
}
public static void main(String[] args) {
Foo<Integer> newFoo = Foo.newFoo();
Bar<Integer, Integer> s = newFoo.toBar();
Bar<Integer, Integer> s2 = Foo.newFoo().toBar();
}
}
main 方法的前两行工作正常。最后一行(Foo.newFoo().toBar()
)给我一个错误:Type mismatch: cannot convert from Bar<Object,Object> to Bar<Integer,Integer>
.有没有办法在一行中做到这一点而不会出错?转换为 Bar<Integer, Integer>
不起作用。
更多是出于好奇而非必要...
最佳答案
这个有效:
Bar<Integer, Integer> s2 = Foo.<Integer>newFoo().toBar();
关于java - 链式方法调用中的通用规范,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45495952/