后面带有大括号的此构造函数调用是什么? [英] What is this constructor call with following double braces?

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

问题描述

不幸的是,我已经有五年没有编写Java编码了,我绝对不记得以下代码的工作方式或原因。

Unfortunately I haven't coded Java for about five years and I absolutely can not remember how or why the following code is working.

我偶然发现了一个类似的例子并将其分解为重点放在注释下面的部分:我没有得到构造函数符号,其后是放在方括号中的块。不幸的是,我在Java文档中或使用Google都找不到任何东西(我应该用谷歌搜索什么词?)。

I stumbled across a similar example and broke it down to this. The emphasis is on the part below the comment: I don't get the constructor notation followed by the block in double brackets. And unfortunately I can not find anything in the Java documentation or by using Google (what word(s) should I google?).

package syntaxtest;

public class Main {

    public static void main(String[] args) {

        // What kind of notation is this?
        MyTest tester = new MyTest() {{
            setName("John Johnson");
        }};

        System.out.println(tester.getName());
    }
}


class MyTest {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

这是我的问题:


  1. 该符号/语法的称呼是什么?

  2. 在哪里可以阅读有关它的文档?

我想/希望我能自己回答第二个问题,如果有人能为我提供第一个问题的答案

I guess/ hope I will be able to answer the second question by myself if somebody can provide me with the answer to the first question.

要明确一点:我知道输出是 John Johnson ;)但是我不知道为什么

To make it clear: I know the output is John Johnson ;) But I don't know why it is working.

推荐答案

这称为 双括号初始化


第一个括号创建一个新的
AnonymousInnerClass,第二个
声明实例初始化程序块
,该实例初始化程序块在实例化匿名内部
类时运行。这种类型的
初始值设定项块正式称为
为实例初始值设定项,因为它在类的实例范围
中声明了
-静态初始值设定项
是一个相关概念,其中将
关键字static放置在启动该块的
括号之前,并且在
完成类加载器加载后立即在类级别执行

类(指定为
http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.6
初始化程序块可以使用任何
方法,字段和最终变量
可用于包含范围,但是
必须警惕
初始化程序要在
构造函数之前运行的事实。

The first brace creates a new AnonymousInnerClass, the second declares an instance initializer block that is run when the anonymous inner class is instantiated. This type of initializer block is formally called an "instance initializer", because it is declared within the instance scope of the class -- "static initializers" are a related concept where the keyword static is placed before the brace that starts the block, and which is executed at the class level as soon as the classloader completes loading the class (specified at http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.6) The initializer block can use any methods, fields and final variables available in the containing scope, but one has to be wary of the fact that initializers are run before constructors.

这仅适用于非最终
类,因为它创建了
匿名子类。

This only works only for non-final classes because it creates an anonymous subclass.

这篇关于后面带有大括号的此构造函数调用是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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