调用一个没有实际参数但具有显式类型参数的泛型方法时发生编译器错误 [英] Compiler error when Calling a generic method with no actual argument but with explicit type parameter

查看:159
本文介绍了调用一个没有实际参数但具有显式类型参数的泛型方法时发生编译器错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从书籍Java Generic and Collections1.4节有这段代码sniplet

  class Lists {
公共静态< T>列表与LT; T> toList(T ... arr){
List< T> list = new ArrayList< T>();
for(T elt:arr)
list.add(elt);
返回列表;


然后有这样的说法:


将类型参数传递给泛型方法调用时,
出现在左边的尖括号中,就像方法
声明。 Java语法要求类型参数只能在使用虚线形式的方法调用中出现
。即使方法
toList在调用代码的同一个类中定义,我们也不能将
缩短为如下所示:

 列表与LT;整数> ints =< Integer> toList(); //编译时错误

这是非法的,因为它会使解析器混淆。


所以我想了解为什么会出现编译时错误。

解决方案


所以我想了解为什么会有编译时错误。

因为这是规范。请参阅 JLS§15.12: p>


方法调用表达式用于调用类或实例
方法。

 
MethodInvocation
MethodName ArgumentList opt
NonWildTypeArguments opt 标识符 ArgumentList opt
super。 NonWildTypeArguments opt 标识符 opt )
ClassName 。超级。 NonWildTypeArguments opt 标识符 ArgumentList opt
TypeName NonWildTypeArguments 标识符(ArgumentList opt


至于为什么规范是这样写的,只有语言设计者才能回答。

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.

解决方案

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.

这篇关于调用一个没有实际参数但具有显式类型参数的泛型方法时发生编译器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆