Category Archives: effectivejava

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.