Posts Tagged static object initialization

How to initialize a static final object

Sometimes I need to intitialize a complex static final object, but I don’t like static blocks for initialization. IMHO it isn’t nice to read!
An alternative way is using an static method:

private static final YourObject defaultYourObject = initYourObject();

private static YourObject initYourObject() {
	try {
		return new YourObject(param1, param2);
	} catch (Exception e) {
		// should never happened
		throw new Error("Could not initialize YourObject", e);
	}
}

And of course, the error-handling is an own special topic in this case!

Advertisements

,

Leave a comment