Alternative using Lombok is use @UtilityClass
annotation.
@UtilityClass
was introduced as an experimental feature in Lombok v1.16.2
:
If a class is annotated with @UtilityClass
,
the following things happen to it:
- It is marked final.
- If any constructors are declared in it, an error is generated.
- Otherwise, a private no-args constructor is generated; it throws a
UnsupportedOperationException
.
- All methods, inner classes, and fields in the class are marked
static
.
Overview:
A utility class is a class that is just a namespace for functions. No instances of it can exist, and all its members are static. For example, java.lang.Math
and java.util.Collections
are well known utility classes.
This annotation automatically turns the annotated class into one.
A utility class cannot be instantiated.
By marking your class with @UtilityClass
, lombok will automatically generate a private constructor that throws an exception, flags as error any explicit constructors you add, and marks the class final.
If the class is an inner class, the class is also marked static.
All members of a utility class are automatically marked as static. Even fields and inner classes.
Example:
import lombok.experimental.UtilityClass;
@UtilityClass
public class FilePathHelper {
private static String resourcesPath;
public static String getFilePath(HttpServletRequest request) {
if(resourcesPath == null) {
ServletContext context = request.getSession().getServletContext();
String serverpath = context.getRealPath("");
resourcesPath = serverpath + "/WEB-INF/classes/";
}
return resourcesPath;
}
}
Reference from official documentation: