From the book "Java Generic and Collections", section 1.4 there is this code sniplet
从“Java Generic and Collections”一书的1.4节中可以看到这段代码片段
class Lists {
public static <T> List<T> toList(T... arr) {
List<T> list = new ArrayList<T>();
for (T elt : arr)
list.add(elt);
return list;
}
}
Then there is this statement:
然后有这样的声明:
When a type parameter is passed to a generic method invocation, it appears in angle brackets to the left, just as in the method declaration. The Java grammar requires that type parameters may appear only in method invocations that use a dotted form. Even if the method toList is defined in the same class that invokes the code, we cannot shorten it as follows:
将类型参数传递给泛型方法调用时,它将显示在左侧的尖括号中,就像在方法声明中一样。 Java语法要求类型参数可能仅出现在使用虚线形式的方法调用中。即使toList的方法是在调用代码的同一个类中定义的,我们也不能按如下方式缩短它:
List<Integer> ints = <Integer>toList(); // compile-time error
This is illegal because it will confuse the parser.
这是非法的,因为它会使解析器混淆。
So I am trying to understand why there would be compiler-time error.
所以我试图理解为什么会出现编译时错误。
1 个解决方案
#1
0
So I am trying to understand why there would be compiler-time error.
所以我试图理解为什么会出现编译时错误。
Because that's to specification. See JLS §15.12:
因为这是规范。见JLS§15.12:
A method invocation expression is used to invoke a class or instance method.
方法调用表达式用于调用类或实例方法。
MethodInvocation: MethodName ( ArgumentListopt ) Primary . NonWildTypeArgumentsopt Identifier ( ArgumentListopt ) super . NonWildTypeArgumentsopt Identifier ( ArgumentListopt ) ClassName . super . NonWildTypeArgumentsopt Identifier ( ArgumentListopt ) TypeName . NonWildTypeArguments Identifier ( ArgumentListopt )
As to why the specification was written that way, only the language designers can answer that.
至于为什么规范是这样编写的,只有语言设计者才能回答这个问题。
#1
0
So I am trying to understand why there would be compiler-time error.
所以我试图理解为什么会出现编译时错误。
Because that's to specification. See JLS §15.12:
因为这是规范。见JLS§15.12:
A method invocation expression is used to invoke a class or instance method.
方法调用表达式用于调用类或实例方法。
MethodInvocation: MethodName ( ArgumentListopt ) Primary . NonWildTypeArgumentsopt Identifier ( ArgumentListopt ) super . NonWildTypeArgumentsopt Identifier ( ArgumentListopt ) ClassName . super . NonWildTypeArgumentsopt Identifier ( ArgumentListopt ) TypeName . NonWildTypeArguments Identifier ( ArgumentListopt )
As to why the specification was written that way, only the language designers can answer that.
至于为什么规范是这样编写的,只有语言设计者才能回答这个问题。