Sunday, April 5, 2009

Java Instance Initializers

I've always been aware of java static initializers, and have been quite comfortable around them
public class Foo {
private static final Map<String, Object> CACHE;
static {
CACHE = new HashMap<String,Object>();
CACHE.put("foo", new Object());
CACHE.put("bar", new Object());
}
}
But I saw this the other day
public class Foo {
private final List<String> emailAddresses;
{
emailAddresses = new ArrayList<String>();
emailAddresses.add("foo@bar.com");
}
}

Did some research and looks like an instance initializer, which is just like a static initializer except is run every time an instance of the class is created.

Very useful if there are multiple constructors for a class, and you don't want to keep running the same initialization code over and over again.

Some interesting examples here

No comments:

About Me

My photo
Melbourne, VIC, Australia
Jerrold is a recently migrated Melbourne based software engineer with roughly 5 years experience developing in Java and the web technology stack (HTML, CSS, DOM, JavaScript, etc). More recently, he's started developing in Python (well, Jython, but close enough) and is unsure if it's flaws outweigh its advantages of having a more sugary syntax. He is currently working at a small South Melbourne based company which specialises in sales incentive management / reporting software, and is being schooled in the finer points of small company operations.