Compiler error when Calling a generic method with no actual argument but with explicit type parameter

独自空忆成欢 提交于 2020-01-17 05:42:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!