问题
From the book "Java Generic and Collections", section 1.4 there is this code sniplet
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:
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:
So I am trying to understand why there would be compiler-time error.
Because that's to specification. See 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.
来源:https://stackoverflow.com/questions/12082519/compiler-error-when-calling-a-generic-method-with-no-actual-argument-but-with-ex