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:

 

public final class UtilityClass {
// Private constructor to prevent instantiation
private UtilityClass() {
throw new UnsupportedOperationException();
}
//public static methods here
}

view raw
UtilityClass.java
hosted with ❤ by GitHub

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

import lombok.experimental.UtilityClass;
@UtilityClass
public class UtilityClassWithLombok {
private final int CONSTANT = 5;
public int addSomething(int in) {
return in + CONSTANT;
}
}

Vanilla:

public final class UtilityClassWithLombok {
private static final int CONSTANT = 5;
private UtilityClassWithLombok() {
throw new java.lang.UnsupportedOperationException("This is a utility class and cannot be instantiated");
}
public static int addSomething(int in) {
return in + CONSTANT;
}
}

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