new之后的构造函数调用中的类型实参的目的是什么? [英] What is the purpose of type arguments in constructor call following new?

查看:58
本文介绍了new之后的构造函数调用中的类型实参的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java规范中(http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9 ),新的格式如下:

In the Java specification (http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.9), new has the following form:

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

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

What is the purpose of the first optional type argument list after the new? I was not able to find it from my read of section 15.9 (all references to type arguments list seem to refer to the list after the type/identifier). Testing out random bits on the standard Java compiler yields confusing results:

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

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

On theses simple examples, it doesn't seem like this first parameter list does anything meaningful although it parses and checks for the validity of its arguments.

推荐答案

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

Constructors can declare type parameters too

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> 的作用.这是构造函数的类型参数.

That's what the <String> preceding the constructor call is for. It is the type argument for the constructor.

以下

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

失败

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

The parameterized constructor Foo(Integer, String) of type Main.Foo is not applicable for the arguments (Integer, Object)

最后一次

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

NotDefined 只是在编译过程中找不到的类型.如果是这样,它只会警告您未使用.

NotDefined is just not a type that is found during compilation. If it was, it would just give you a warning that it is unused.

这篇关于new之后的构造函数调用中的类型实参的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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