A new way to init Java objects!
Well you learn something new every day. Initializing Java objects can be a chore, and especially when initializing static data in collections, where the collections are fields of another object.
Well some smart cookie found a way to use the standard anonymous class mechanism of Java to do initialization that means you don’t need to specify the name of the object, and can bind the initialization code to the field definition. Basically when you construct the object you do so as an anonymous class and use the instance initializer block to access fields or methods of the object.
Where in the past you might do:
public class Test {
private List creditCards = new ArrayList();
{
creditCards.add( "VISA");
creditCards.add( "MC");
creditCards.add( "AMEX");
}
}
You can do:
public class Test {
private List creditCards = new ArrayList() {
{
add( "VISA");
add( "MC");
add( "AMEX");
}
};
}
It’s pretty cool. The only sideeffect is that the creditCards field will be of a type that extends ArrayList, i.e. something like Test$1.
Who would have thought we could find out something new about fundamental features of Java after all these years?
Note: Sorry about the crappy source formatting, WordPress doesn’t like preformatted text.
No related posts.