java 如何在Java中初始化匿名内部类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5310403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 10:33:38  来源:igfitidea点击:

How to initialize anonymous inner class in Java

java

提问by Jarek

Is there any way to initialize anonymous inner class in Java?

有没有办法在Java中初始化匿名内部类?

For example:

例如:

new AbstractAction() {
    actionPerformed(ActionEvent event) {
    ...
    }
}

Is there any way to use for example putValue method somewhere in the class declaration?

有没有办法在类声明中的某处使用例如 putValue 方法?

回答by Sean Patrick Floyd

Use an Initializer Block:

使用初始化块:

new AbstractAction() {

    {
        // do stuff here
    }

    public void actionPerformed(ActionEvent event) {
    ...
    }
}


Initializing Instance Members

初始化实例成员

Normally, you would put code to initialize an instance variable in a constructor. There are two alternatives to using a constructor to initialize instance variables: initializer blocks and final methods. Initializer blocks for instance variables look just like static initializer blocks, but without the static keyword:

通常,您会在构造函数中放置用于初始化实例变量的代码。使用构造函数初始化实例变量有两种替代方法:初始化块和最终方法。实例变量的初始化块看起来就像静态初始化块,但没有 static 关键字:

{
    // whatever code is needed for initialization goes here
}

The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.

Java 编译器将初始化块复制到每个构造函数中。因此,这种方法可用于在多个构造函数之间共享代码块。

Source:

来源:

回答by Jon Skeet

It's not quite clear what you mean, but you can use an initializer blockto execute code at construction time:

不是很清楚你的意思,但你可以在构造时使用初始化块来执行代码:

new AbstractAction() {

    {
        // This code is called on construction
    }

    @Override public void actionPerformed(ActionEvent event) {
    ...
    }
}

回答by weekens

You can use the instance initialization section:

您可以使用实例初始化部分:

new AbstractAction() {
    {
       //initialization code goes here
    }

    actionPerformed(ActionEvent event) {
    ...
    }
}

回答by Philipp Hügelmeyer

Or you can just access the variables of the outer class from the inner class.

或者你可以只从内部类访问外部类的变量。

http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes#Anonymous_Classes

http://en.wikibooks.org/wiki/Java_Programming/Nested_Classes#Anonymous_Classes