Non-instantiable class

Sometimes we need to develop a class Helper, also known as Utility class, contain a group of reusable methods across the application. As an example consider Apache StringUtils or IOUtils. It is stateless frequently with methods as static and cannot be instantiated.

We can eliminate the instantiation of default constructor with an explicit private constructor and an Exception to indicate that the requested operation is not supported, it guarantees the class will never be instantiated under any circumstances:

 

By marking your class with @UtilityClass, lombok will automatically generate a private constructor that throws an exception:

Vanilla:

The full implementation of this tutorial can be found over on GitHub.

1 thought on “Non-instantiable class

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 )

Google photo

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