java中的双{{}}语法问题 [英] Double {{ }} syntax question in java
问题描述
假设我通过以下方式创建了一个JMenu Bar:
Assume I created a JMenu Bar the following way:
JMenuItem saveMenuItem = new JMenuItem("Save")
{{
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
String location = GUI.Custom.QuickDialogs.selectFile(false);
try
{
PrintWriter pw = new PrintWriter(new File(location));
String text = textArea.getText();
pw.println(text);
pw.flush();
pw.close();
}
catch(Exception ex)
{
textArea.append("Could not save this debug output");
}
}
});
}};
JMenu optionsMenu = new JMenu("Options")
{{
add(saveMenuItem);
setVisible(true);
}};
private JMenuBar menuBar = new JMenuBar()
{{
add(optionsMenu);
setVisible(true);
}};
这是一种糟糕的设计模式,以这种方式创建对象,而不是仅仅声明变量,然后在构造函数或其他东西中创建?
Is this a bad design pattern to create objects this way as opposed to just declaring the variable, and then creating in a constructor or something?
推荐答案
你所做的是:初始化块。
What you've done is called: "initialization block".
来自 doc:
Java编译器将初始化程序
块复制到每个构造函数中。
因此,这种方法可以用
来共享
多个构造函数之间的代码块
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors
示例:
class A {
private String field1;
{
field1 = "example field";
field2 = getstaticResult();
}
}
但在我看来,我们不应该'经常使用它,特别是在你的情况下使用它是非常不寻常的。
But in my opinion we shouldn't use this very often and especially in your case it's very unusual to use it.
这篇关于java中的双{{}}语法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!