Java Deep

Pure Java, what else

How to instantiate utility class

In a previous blog we had a look how to protect utility classes to be instantiated. We finally got to this class:

public final class YouJustCanNotInstantiate {
    private YouJustCanNotInstantiate() {
        throw new RuntimeException("You just can not instantiate this class.");
    }
}

Seems to be a tough guy. Still there are ways to get an instance of this class:

Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
Unsafe unsafe = (Unsafe) f.get(null);
YouJustCanNotInstantiate s1 = (YouJustCanNotInstantiate) unsafe.allocateInstance(YouJustCanNotInstantiate.class);

It works fine on ORACLE JVM, but be aware that this is not standard and may not work on other JVMs. Actually there is no guaranteed Java way that always works. However there is a project called Objenesis that does the trick and works on Android, Rockit, Gcj and Perc JVM in addition to the “standard” ORACLE JVM. Have a look at it! It is an interesting project at least to learn from.

WARNING: if a class was not meant to be instantiated and was protected from that the way above, then you will deserve what you get following this pattern. You have been warned.

Credit: Yuriy Fuksenko, and Norbert Madarász for pointing out these solutions on LinkedIn

Advertisements

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: