在下面的示例中,为什么编译器能够推断Foo.test()
中第一次调用Foo.create()
的通用参数,但第二次不能这样做?我使用Java 6为什么javac不能推断用作参数的函数的泛型类型参数?
public class Nonsense {
public static class Bar {
private static void func(Foo<String> arg) { }
}
public static class Foo<T> {
public static <T> Foo<T> create() {
return new Foo<T>();
}
private static void test() {
Foo<String> foo2 = Foo.create(); // compiles
Bar.func(Foo.create()); // won't compile
Bar.func(Foo.<String>create()); // fixes the prev line
}
}
}
(编译错误是在类型Nonsense.Bar的方法FUNC(Nonsense.Foo)不适用于参数(Nonsense.Foo))。
注意:我知道编译器错误可以通过test()中的第三行修复 - 我很好奇是否存在一个特定的限制,防止编译器能够推断出类型。它出现对我来说,这里有足够的上下文。
我不确定你期望得到什么答案,除了“它不够聪明”。 –
@路易斯 - 可以想象,这是不可能够聪明,但我还没有弄清楚为什么。 – bacar
@bacar:它可能足够聪明,但它不是。 –