Java Syntactic Sugar

geowa4 picture geowa4 · Oct 5, 2010 · Viewed 7.4k times · Source

I ran into this block of code today, and I don't know how it works. I know how to make anonymous classes, but I'm used to seeing a method signature and not just a pair of braces. Is the code between those braces put into a static block? Does it go into the constructor? Or is it something else altogether?

conext.checking(new Expectations() {
    { // <- what does this pair of braces do?
        oneOf(alarm).getAttackAlarm(null);
    }
});

Answer

Reverend Gonzo picture Reverend Gonzo · Oct 5, 2010

It's an instance initializer that calls the code within the context of the created object.

This is equivalent to

Expectations exp = new Expectations();
exp.oneOf(alarm).getAttackAlarm(null);
conext.checking(exp)

Whoever wrote it might have thought he was being more efficient by not declaring a variable (not true) or that it was cleaner code (I disagree).

The primary place that these initializers are useful like this is when instantiating maps, ie:

Map map = new HashMap() {{
  put("key1", "value1");   
  put("key2", "value2"); 
}};

which I think actually is slightly more readable.