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");
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


Leave a Reply

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

You are commenting using your 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.