小编典典

new之后的构造函数调用中的类型实参的目的是什么?

java

在Java规范(http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9)中,new具有以下形式:

ClassInstanceCreationExpression ::=
| new TypeArguments_opt TypeDeclSpecifier TypeArgumentsOrDiamond_opt
    ( ArgumentListopt ) ClassBodyopt
| Primary . new TypeArguments_opt Identifier TypeArgumentsOrDiamond_opt
    ( ArgumentListopt ) ClassBodyopt

新版本之后的第一个可选类型参数列表的目的是什么?通过阅读第15.9节,我找不到它(对类型实参列表的所有引用似乎都在类型/标识符之后引用该列表)。在标准Java编译器上测试随机位会产生令人困惑的结果:

public class Foo<T> { }
// ...
Foo<Integer> t1 = new <Integer> Foo<Integer>();  // works
Foo<Integer> t2 = new <Integer> Foo();           // works -- unchecked warning missing the type arg after Foo
Foo<Integer> t3 = new <Boolean> Foo<Integer>();  // works
Foo<Integer> t4 = new <Float, Boolean> Foo<Integer>();  // works
Foo<Integer> t5 = new <NotDefined> Foo<Integer>();  // fails -- NotDefined is undefined

在这些简单的示例中,尽管第一个参数列表解析并检查了其参数的有效性,但似乎没有做任何有意义的事情。


阅读 174

收藏
2020-11-16

共1个答案

小编典典

构造函数也可以声明类型参数

public class Main {     
    public static class Foo<T> {
        public <E> Foo(T object, E object2) {

        }
    }
    public static void main(String[] args) throws Exception {
        Foo<Integer> foo = new <String> Foo<Integer>(1, "hello");           
    }    
}

这就是<String>前面的构造函数调用的目的。它是构造函数的类型参数。

下列

Foo<Integer> foo = new <String> Foo<Integer>(1, new Object());

失败于

Main.Foo类型的参数化构造函数Foo(Integer,String)不适用于参数(Integer,Object)

在你的最后

Foo<Integer> t5 = new <NotDefined> Foo<Integer>();  // fails -- NotDefined is undefined

NotDefined只是在编译过程中找不到的类型。如果是的话,只会警告您它是unused

2020-11-16