Lombok Annotations

Unlocking the Power of Lombok Annotations: Simplifying Your Java Code

Anji…

--

In this article, we would like to do a deep dive into the Lombok and Lombok annotations.

What is Lombok?

Lombok is a Java library that allows developers to generate code at compile time. i.e., by leveraging the Lombok-provided annotations, you can minimize the boilerplate code and avoid repetitive code. Lombok has become increasingly popular among Java developers because of its ability to simplify code and improve readability.

How do I add Lombok to the project?

Please ensure you have added the Lombok plugin to IntelliJ. Once the plugin is installed, please ensure the annotation processor is enabled. The annotation processor is disabled by default. You can enable them by navigating to File -> Settings -> Build, Execution, Deployment -> Compiler -> Annotation Processors

Add Lombok to Maven Project

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
<scope>provided</scope>
</dependency>

Add Lombok to Gradle Project

compileOnly 'org.projectlombok:lombok:1.18.24'

Most used Annotations

Below are the most used annotations as part of the developer's day-to-day job.

@Getter & @Setter: Generates the getter and setters for the class fields.

@ToString: generates a toString implementation for the class fields. This can be used with multiple other combinations to get the desired outcome.

@ToString(callSuper = true): includes the super class toString implementation output in the generated toString output.

@ToString(exclude = “fieldName”): excludes the specified fields from the toString output. Please note that this is the old way of excluding. Instead of defining it at the class level, you can define the @ToString.Exclude at the property level.

@ToString(of = { “property 1”, “property 2” }): includes the properties as part of the ToString output. You can also define it at the property level using @ToString.Include annotation at the property level.

@ToString(onlyExplicitlyIncluded = true): includes only the fields explicitly included in the ‘of’ parameter and excludes all other fields from the generated toString() output.

@ToString(includeFieldNames = false): excludes the field names from the generated toString() output.

@ToString(doNotUseGetters = true): includes the field values directly in the generated toString() output, without calling the getters.

@ToString(onlyExplicitlyIncluded = true): includes only the fields explicitly included in the parameter and excludes all other fields from the generated toString() output.

@ToString(implementation = CustomToString.class): Uses the specified class to generate the toString() method implementation.

@NonNull: Generates null checks for method parameters and fields.

@NoArgsConstructor: Generates the No Arguments constructor. You can define the access level using the access input value for the annotation

@AllArgsConstructor: Generates the constructor with all the fields.

@RequiredArgsConstructor: Generates the constructor with the fields that is annotated with @NotNull or defined as a final field.

@EqualsAndHashCode: Generates equals() and hashCode() methods based on the fields of the class.

@Data: Combines the functionality of @Getter, @Setter, @ToString, @EqualsAndHashCode, and @RequiredArgsConstructor annotations.

@Builder: Generates a builder pattern for the class, allowing you to construct objects with a fluent API.

@Log: Generates a logger field for the class.

@Slf4j: Generates a logger field for the class using the SLF4J library.

@Log4J2: generates a logger field for the class using Log4J2

@Cleanup: Automatically closes resources such as streams and connections. It cleans up the resources before leaving the current scope.

Note that this annotation works by harnessing the try-with-resources statement.

@Synchronized: Generates synchronized blocks for methods or blocks.

@UtilityClass: Generates a utility class with a private constructor and static methods only.

@FieldNameConstants: Generates a class with constants for all field names in the annotated class.

@ExtensionMethod: Allows adding methods to existing classes without subclassing or modifying the original class.

@EqualsAndHashCode.Exclude: Excludes a field from the generated equals() and hashCode() methods.

@SuppressWarnings(“all”): Suppresses all warnings for the annotated element.

@NonNullFields: Applies the @NonNull annotation to all fields in the annotated class.

@NonNullApi: Applies the @NonNull annotation to all method parameters and returns values in the annotated.

@SneakyThrows: It is used to sneakily throw checked exceptions without actually declaring them in your method’s throws clause.

If you would like to take a look at the generated code with Lombok annotations, you can navigate as below in IntelliJ and generate the code.

Masking Data using Lombok

One of the frequent requirements that we come across is masking the data when logging the information. Lombok doesn’t have any annotations pertinent to the masking. However, there is a way to do it. Below is the class definition to mask the sensitive data

@Data
public class LoginModel {
private String loginId;
@ToString.Exclude
private String password;

@ToString.Include(name = "password")
private String maskPassword() {
return "******";
}
}

When you call ‘ToString’ on the LoginModel, you will see the log as below.

LoginModel(loginId=null, password=******)

Pros and Cons

Pros

  • Open source
  • Improves developer productivity by generating the boilerplate code
  • Makes your code concise and clear

Cons

  • IDE plugins are needed
  • Need to be a little careful when using Lombok with JPA entities
  • debugging challenges

That’s all we have for today. Please share your thoughts in the comment box.

--

--

Anji…

Technology Enthusiast, Problem Solver, Doer, and a Passionate technology leader. Views expressed here are purely personal.