Lombok is an useful project created to remove the boilerplate code and you can concentrate on your code.
you can add lombok jar using following maven dependency:
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.8</version>
<scope>provided</scope>
</dependency>
</dependencies>
And we can add logs, commons and more to ease our programming.
Person.java:
import
lombok.AllArgsConstructor;
import lombok.Builder;
import
lombok.EqualsAndHashCode;
import lombok.Getter;
import
lombok.NoArgsConstructor;
import lombok.Setter;
import
lombok.ToString;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor(staticName="of")
@EqualsAndHashCode(of={"name","age"})
@Builder
@ToString
public class Person {
private String name;
private int age;
private String description;
public static void main(String[] args) {
Person
aPerson = new Person();
aPerson.setName("Lenin");
aPerson.setAge(29);
aPerson.setDescription("Software
Engineer");
System.out.println(aPerson.getAge());
System.out.println(aPerson.getName());
System.out.println(aPerson.getDescription());
Person
bPerson = Person.of("Lenin", 29, "Software Engineer");
System.out.println(aPerson.equals(bPerson));
Person
person = Person.builder().name("Lenin").age(29).description("Engineer").build();
System.out.println(person);
}
}
you can implement same using @Data annotation with less code.
import
lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import
lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor(staticName="of")
@Builder
public class Person {
private String name;
private int age;
private String description;
public static void main(String[] args) {
Person
aPerson = new Person();
aPerson.setName("Lenin");
aPerson.setAge(29);
aPerson.setDescription("Software
Engineer");
System.out.println(aPerson.getAge());
System.out.println(aPerson.getName());
System.out.println(aPerson.getDescription());
Person
bPerson = Person.of("Lenin", 29, "Sr.
Software Engineer");
System.out.println(aPerson.equals(bPerson));
Person
person = Person.builder().name("Lenin").age(29).description("Engineer").build();
System.out.println(person);
}
}
No comments:
Post a Comment