Lombok with Java for everyday use — Part 2!!!

Athul RAVINDRAN
2 min readJan 23, 2020

--

Welcome to Part 2..thanks for reading Part 1.

In this section, lets see the remaining fun part of Lombok that I have used.

  1. @Builder —Click here I have a separate story for it.
  2. @Data — This is a cool annotation and I call it so because, it combines all of the most useful annotations into one powerful annotation making your life so easy when dealing with POJOs / beans / value objects or what ever you wanna call it.

@Data = @ToString + @EqualsAndHashCode+ @Getter + @Setter+ @RequiredArgsConstructor

Here is an example. PersonLombok class in the screenshot from Part 1 @Getter / @Setter and @ToString becomes like this

@Data
@Slf4j
public class PersonLombok {

private String firstName;
private String lastName;
private int age;

@Tolerate
public String getLastName(String firstName) {

if(firstName == null)
{
return "FNU" + lastName;
}
else
{
return lastName;
}
}


public void exampleOfLogging()
{
log.info("Lombok - Spice up your java !!");
}
}

2) @NoArgsConstructor — Annotating a class with @NoArgsConstructor creates a constructor with no parameters. If all the member variables of the class is final, will result in a compiler error. This could be handled by forcing lombok to initialize final variables — @NoArgsConstructor(force=true).

3) @AllArgsConstructor — same as @NoArgsConstructor but in this case, a constructor is created with 1 parameter for every field in the class.

4) @RequiredArgsConstructor — generates a constructor requiring an argument for the final and @NonNull fields. This will force the caller class to pass a value for each parameter in the constructor while creating a new instance of the annotated class.

All the above 3 constructor annotations offers creating a static factory method. @RequiredArgsConstructor(staticName = “of”) is an example.

This would create a the following

public static RequiredArgsConstructorVanilla to (String name, String department)
{
this.name = name;
this.department = department;
}

5) @UtilityClass — This is a very handy annotation for creating a true Util class. What I mean by true Util class is — all methods are static and variables of the class is final static constants.

By annotating a class with @UtilityClass, lombok generates a private constructor, so no caller can create a new instance and as well as makes all member variables and methods static.

--

--