85% Discount for all November
Software Development
Computer Software
Coding
Though Java is a great language, we still need to write the boilerplate codes in Java such as getters, setters, toString method. Project Lombok is a java library tool which is used to minimize/remove the boilerplate code.
a) It uses annotations
b) Increases the readability of the source code.
c) Saves space and developer’s time.
To use Lombok in your project.
You can use Lombok by adding the following to your build.gradle in the dependencies block:
compileOnly "org.projectlombok:lombok:1.18.16”
Lombok annotations
@Data : Generates all the boilerplate that is normally associated with simple POJOs (Plain Old Java Objects) and beans. @Data is like having implicit @Getter, @Setter, @ToString, @EqualsAndHashCode and @RequiredArgsConstructor annotations on the class
Some of the other annotations are
@NoArgsConstructor : Generates constructor that takes no arguments
@RequiredArgsConstructor: Generates constructor with one argument per final / non-null field
@AllArgsConstructor : Generates constructor with one argument for every field.
@Builder : Generates the code required to have your class be instantiable using the builder pattern.
@ToString : Generates the toString() method in the ".class" file at compile time.
@Getter and @Setter : Generates getter and setter methods for a field respectively. These annotations can be used at the field and class level.
@NonNull : You can use @NonNull annotation on the parameter of constructor or a method to generate null checks.
@EqualsAndHashCode:Generates hashCode and equals implementations from the fields of your object.
@Slf4j, @Log, @CommonsLog, @Log4j, @Log4j2, @XSlf4j :Generates the code to get the logger of our choice for logging purposes. Example given below.
Conclusion
Lombok can be useful for making your code more concise, reducing the chance for bugs, and speeding up development time.Try adding Lombok to one of your applications and see how many lines of code you can cut out.
Monday, Apr 26, 2021