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

,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: