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:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public final class UtilityClass { | |
| // Private constructor to prevent instantiation | |
| private UtilityClass() { | |
| throw new UnsupportedOperationException(); | |
| } | |
| //public static methods here | |
| } |
By marking your class with @UtilityClass, lombok will automatically generate a private constructor that throws an exception:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import lombok.experimental.UtilityClass; | |
| @UtilityClass | |
| public class UtilityClassWithLombok { | |
| private final int CONSTANT = 5; | |
| public int addSomething(int in) { | |
| return in + CONSTANT; | |
| } | |
| } |
Vanilla:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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.
