Java Double Brace Initialization

I’m a fan of the JMockit framework, which if you’ve used you’ll surely be familiar with it’s “double brace” syntax. For example:


new Expectations() {{
// ...
}}

While I’ve seen and used the double braces in JMockit, and done a bit of a double take, I’d never gotten around to figuring out what was actually going on there.

What are Those Double Braces?

Today, out of the blue, I came across a post about them, and it too just breezed by the “what” and went straight to a tip employing them.

Okay, I wasn’t going to ignore this again. So what is that double brace syntax?

It Isn’t a Thing

There is no “double brace syntax”. It’s actually a combination of two things, one fairly common, one more esoteric. A good discussion can be found here.

The concise answer is, it an anonymous class declaration, combined with an instance initializer block. A what? It’s an alternative to a constructor, and you’ve likely seen them associated only with static initialization. Who was to know there are instance initializer blocks too?

So, the double brace is a way to create and anonymous class and provide a constructor in one go. If you read the first article I referenced, they use it for adding content to collections at creation time.

Live and learn… if you bother to.

Advertisements