Lombok Project
  • Features
    • Stable
    • Experimental
  • Community
    • Discuss / Help
    • Issues
    • Documentation for contributors
    • Contact the team behind Project Lombok
  • Order / Donate
  • How to use Install
    • Compilers
    • Javac
    • ECJ
    • Build tools
    • maven
    • gradle
    • ant
    • kobalt
    • IDEs
    • Eclipse
    • IntelliJ IDEA
    • Netbeans
    • MyEclipse
    • Spring Tool Suite
    • JBoss Developer Studio
    • Visual Studio Code
    • Platforms
    • Android
    • GWT
  • Download

@UtilityClass

Utility, metility, wetility! Utility classes for the masses.

@UtilityClass was introduced as an experimental feature in lombok v1.16.2.

Experimental

Experimental because:
  • Some debate as to whether its common enough to count as boilerplate.
Current status: positive - Currently we feel this feature may move out of experimental status with no or minor changes soon.

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.

With Lombok

import lombok.experimental.UtilityClass;

@UtilityClass
public class UtilityClassExample {
  private final int CONSTANT = 5;

  public int addSomething(int in) {
    return in + CONSTANT;
  }
}

Vanilla Java

public final class UtilityClassExample {
  private static final int CONSTANT = 5;

  private UtilityClassExample() {
    throw new java.lang.UnsupportedOperationException("This is a utility class and cannot be instantiated");
  }

  public static int addSomething(int in) {
    return in + CONSTANT;
  }
}

Supported configuration keys:

lombok.utilityClass.flagUsage = [warning | error] (default: not set)
Lombok will flag any usage of @UtilityClass as a warning or error if configured.

Small print

There isn't currently any way to create non-static members, or to define your own constructor. If you want to instantiate the utility class, even only as an internal implementation detail, @UtilityClass cannot be used.

credits | Copyright © 2009-2019 The Project Lombok Authors, licensed under the MIT license.