Cool Java code: anonymous class plus instance initializer
#
Check out this code example:
Map options = new HashMap() {{
put("key", "value");
put("option", "foo");
put("flag", "bar");
}};
Ryan calls it a "little-known Java feature called an initializing block":
Huh! I didn't know you could do that. So I tried to figure out how it works. It's interesting. I've used both components separately, but never put them together like this.
The first set of { } creates an anonymous class as a subclass of HashMap. You see this type of code a lot, especially for event listeners. They're also nice for FileFilters.
The second { } I've also used before, but it is rare. It's an instance initializer. (See also this discussion of them.)
So basically you're creating a subclass of HashMap and then setting the values you want in its instance initializer. Clever.
I ran this code in BeanShell and sure enough it reported the class of the instance as "global$1" instead of HashMap.
I ran this past my friend Nick and he replied with another neat trick:
I've used the new <someclass>() {} trick so that I can distinguish between classes in the debugger.
Eg.,
class X {
Map m = new HashMap() {};
}
class Y {
Map m = new HashMap() {};
}
The debugger will say X$1, instead of HashMap -- useful when debugging deadlocks and it isn't clear which object is in contention.