Lombok is an opensource project that reduces boiler plate code in the Java Pojo's by using annotations in the class. The main advantage of Lombok is to get rid of generating getters & setters (although the IDE generates it).
The source code can be found in GitHub.
Lombok in Action:
Add the dependency in pom.xml
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
<scope>provided</scope>
</dependency> |
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@ToString
@NoArgsConstructor
@EqualsAndHashCode
public class Book {
private int id;
private String name;
private String author;
} |
Other useful Annotations:
@ToString
@Builder
@RequiredArgsConstructor
@AllArgsConstructor and lot more ..
IDE's like Eclipse & IntelliJ does not detect the lombok annotations by default.
Lombok in IntelliJ:
Go to File → Settings → Plugins → Browse Repositories. Search for lombok.
Lombok in Eclipse:
Download Lombok and run the Jar. Specify the eclipse location and click Install.
Check the eclipse installation of lombok in About eclipse.
Sample Generated class file:
Code Block | ||||||
---|---|---|---|---|---|---|
| ||||||
public class Book
{
private int id;
private String name;
private String author;
public void setId(int id)
{
this.id = id;
}
public void setName(String name)
{
this.name = name;
}
public void setAuthor(String author)
{
this.author = author;
}
public String toString()
{
return "Book(id=" + getId() + ", name=" + getName() + ", author=" + getAuthor() + ")";
}
public boolean equals(Object o)
{
if (o == this) {
return true;
}
if (!(o instanceof Book)) {
return false;
}
Book other = (Book)o;
if (!other.canEqual(this)) {
return false;
}
if (getId() != other.getId()) {
return false;
}
Object this$name = getName();Object other$name = other.getName();
if (this$name == null ? other$name != null : !this$name.equals(other$name)) {
return false;
}
Object this$author = getAuthor();Object other$author = other.getAuthor();return this$author == null ? other$author == null : this$author.equals(other$author);
}
protected boolean canEqual(Object other)
{
return other instanceof Book;
}
public int hashCode()
{
int PRIME = 59;int result = 1;result = result * 59 + getId();Object $name = getName();result = result * 59 + ($name == null ? 43 : $name.hashCode());Object $author = getAuthor();result = result * 59 + ($author == null ? 43 : $author.hashCode());return result;
}
public int getId()
{
return this.id;
}
public String getName()
{
return this.name;
}
public String getAuthor()
{
return this.author;
}
} |
Other useful Reference: