Double {{ }} syntax question in java
Possible Duplicates:
Efficiency of Java “Double Brace Initialization”?
Meaning of new Class(…){{…}} initialization idiom
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".
From doc:
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors
Example:
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.
Nothing actually wrong with Double Brace Initialization; I often use it for maps and lists.
It maybe depends on who your audience is -- do the other people on your team understand what you're doing here? Remember that someday, somebody is going to have to read this code.
You seem to be asking (at least) two different things here. The double-bracket idiom is known and often used as a shorthand for creating anonymous inner classes, replacing the explicit constructor with an initializer block. Usually this makes the code more readable, so I would say it's OK.
OTOH since (nonstatic) initializer blocks are a relatively recent addition to the language, some developers may not be familiar with them though, which may create confusion. And of course, as with almost any techniques, when overused, it can create more problems than it solves.
链接地址: http://www.djcxy.com/p/82388.html下一篇: java中的双{{}}语法问题