Friday, July 8, 2016

Lombok : Utility project to clear boilerplate code from java classes


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>



Here,  i have created a java bean using lombok annotation to create setters, getters, hascode, equals, toString, builder methods and constructors.

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);
      }
}

Reference:
Project Lombok

No comments:

Post a Comment