Lombok
Lombok project is a library that adds many missing features into Java language. Lets have a look what we can use to speed up our development and make Java code more concise, error prone and readable.
Before we start, lets make sure we can build our project and we can work with lombok in our IDE (IntelliJ IDEA).
Setup IDE
We need to do two things to get lombok working in our IDE.
Instead of manual IDE configuration, we can use
net.ltgt.apt-idea
ornet.ltgt.apt-eclipse
in Gradle to automatically configure what we did above.
Setup Project
We are going to use Gradle code and build management tool. Here is everything what is needed to get lombok project working.
There are no special tasks to work with lombok. The plugin net.ltgt.apt will do the Java annotation processing which we have enabled in IDEA in previous chapter.
Domain Objects
When making a domain objects or DTO (Data Transformation Objects) in pure Java, it is all about description of data using classes, private fields, getter and setter methods. But what we want to do is something like this:
We just want to say type name, what fields it contains and what are the types of the fields. Unfortunattely we need to provide getters and setters in pure Java. But lombok gives us annotations that will enhance the bytecode and provide us with getters and setters for non final fields. Also there is an annotation to generate the constructor with all the fields.
When we use these annotations we can write code like this:
But trying to set id would give us compilation error.
We can use @Data annotation for domain objects that will apply many annotations in once (all these @ToString, @EqualsAndHashCode, @Getter, @Setter, @RequiredArgsConstructor).
Equals and Hash Code
In pure Java, we need to provide proper implementations of equals
and hashCode
methods, otherwise we could face to performance and functional issues.
We can annotate class with @EqualsAndHashCode
annotation to provide generated equals
and hashCode
methods from all field in the class.