java - 链式方法调用中的通用规范

标签 java generics

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/

相关文章:

Java:三元运算符,没有按预期工作

java - 创建类型对象的通用列表并添加字符串

具有下限类型的 Java 类型推断

java - WELD OSGI 示例 - 无结果

java - 如何卸载 Scala Eclipse 插件?

java - 快速 java/python/C++ ipc

java - 拖放图像按钮有 onDrag 问题

c# - 具有通用类参数和转换的函数

generics - 为什么在关联类型上无法识别除第一个之外的超特征边界?

java - 使用invokedynamic时的泛型信息