The limits of double-brace initialization

28 Dec 2011

One thing I miss in Java is C#'s in-line object initialization syntax, where you can create the new object and set properties all in the same statement. So take something like this:


	private class Cat
{
    // Auto-implemented properties.
    public int Age { get; set; }
    public string Name { get; set; }
}
 
Cat cat = new Cat { Age = 10, Name = "Fluffy" };

That's nice and Java didn't seem to have it. Well, it does but it's just not very well advertised. It's called double-brace initialization. It actually works a bit differently, but is similar enough. Once you've created a new object (including passing parameters to the constructor), you just follow up with double braces and insert a bunch of statements without qualifying the owning object:


	GridBagConstraints SPANNING = new GridBagConstraints() {{
    gridx = 0;
    gridwidth = 2;
    insets = new Insets(8, 0, 0, 0);
}};

Great! But... I'm not really sure why this happens, but delegates and listeners don't seem to work properly. So I did something like this:

 

private final JDateChooser _dateChooser = new JDateChooser() {{ addPropertyChangeListener("date", this); }};
The containing class implements the PropertyChangeListener interface. With this configuration, my propertyChange() method isn't invoked when a property is changed. If I remove the double-brace initialization, though, and move listener configuration into the constructor, all is well.
 
So an interesting limitation on this technique. I don't know if this is such a great idea anyways: lots of people are unfamiliar with the syntax, there are some questions about performance, and the Java site itself doesn't seem to be a great deal of help in this regard. But, FWIW...