Project Lombok
Project Lombok aims to reduce the boilerplate code in Java applications. These include getters, setters, toString, Null checks etc. Project Lombok provides a useful set of annotations for eliminating boilerplate code from Java classes. This makes the code concise and easy to maintain. Project Lombok integrates into the IDE and build process and generates byte code based on the annotations specified.
Reference: http://projectlombok.org
As an example, adding a @Data annotation to the insurance info data class below will automatically generate number of new methods in the IDE. This avoids the boilerplate code we would otherwise be writing.
Project Lombok Installation
Steps to install Project Lombok in IDE. Tried on STS “Spring Tools 4 for Eclipse” and it seems to work without issues.
- Download Project Lombok as a jar here
- Launch Jar file from the command line "java -jar Lombok.jar"
- Installer will discover the IDEs installed. If not listed, use the specify location to identify the IDE.
- Perform Install/ Update to complete the installation
- Restart the IDE
- To setup Lombok with any build tool, dependency needs to be specified to specify the source code. For Maven include the Lombok dependency to the pom.xml as below.
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.22</version> <scope>provided</scope> </dependency>
Project Lombok Annotations
This sections lists some of the common Lombok annotations with examples.@Getter and @Setter
Purpose: Annotate any field to let Lombok generate the default getter/ setter automatically.Example: In this insurance info class, we add the annotations on specific fields for generating getter/ setter methods.
package com.stackstalk; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; public class InsuranceInfo { @Getter @Setter private String type; @Getter @Setter private Integer premium; @Getter @Setter private Integer sumInsured; @Getter @Setter(AccessLevel.PROTECTED) private String claimProcess; }
@ToString
Purpose: Any class definition may be annotated with @ToString to let lombok generate an implementation of the toString() method.Example: In this insurance info class, we add the @ToString annotation to the class definition to generate toString method.
package com.stackstalk; import lombok.AccessLevel; import lombok.Getter; import lombok.Setter; import lombok.ToString; @ToString public class InsuranceInfo { @Getter @Setter private String type; @Getter @Setter private Integer premium; @Getter @Setter private Integer sumInsured; @Getter @Setter(AccessLevel.PROTECTED) private String claimProcess; }
@EqualsAndHashCode
Purpose: Any class definition may be annotated with @EqualsAndHashCode to let lombok generate implementations of the equals(Object other) and hashCode() methods.Example: In this insurance info class, we add the @EqualsAndHashCode annotation to the class definition to generate hashCode and equals methods.
package com.stackstalk; import lombok.AccessLevel; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; @ToString @EqualsAndHashCode public class InsuranceInfo { @Getter @Setter private String type; @Getter @Setter private Integer premium; @Getter @Setter private Integer sumInsured; @Getter @Setter(AccessLevel.PROTECTED) private String claimProcess; }
@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor
Purpose: Generates constructors that take no arguments, one argument per final / non-null field, or one argument for every field.Example: In this insurance info class, we add the @AllArgsConstructor annotation to the class definition to generate constructors.
package com.stackstalk; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.ToString; @ToString @EqualsAndHashCode @AllArgsConstructor public class InsuranceInfo { @Getter @Setter private String type; @Getter @Setter private Integer premium; @Getter @Setter private Integer sumInsured; @Getter @Setter(AccessLevel.PROTECTED) private String claimProcess; }
@Data
Purpose: @Data is a convenient shortcut annotation that bundles the features of @ToString, @EqualsAndHashCode, @Getter / @Setter and @RequiredArgsConstructor together.Example: In this insurance info class, we add the @Data annotation to the class definition to generate boilerplate code that is normally associated with simple POJOs.
package com.stackstalk; import lombok.Data; @Data public class InsuranceInfo { private String type; private Integer premium; private Integer sumInsured; private String claimProcess; }
@NotNull
Purpose: @NonNull will cause lombok generate a null-check statement.Example: In this example we add @NonNull to method parameter which generates a null check.
import lombok.Data; import lombok.NonNull; public class NonNullTest { @Data class Employee { private Integer empId; private String empName; } public static void mymethod(@NonNull Employee employee) { System.out.println(employee.getEmpName()); } public static void main(String[] args) { Employee employee = null; mymethod(employee); } }
Output:
Exception in thread "main" java.lang.NullPointerException: employee is marked non-null but is null at com.stackstalk.NonNullTest.mymethod(NonNullTest.java:14) at com.stackstalk.NonNullTest.main(NonNullTest.java:20)
@Cleanup
Purpose: @Cleanup can be used to ensure a given resource is automatically cleaned up before the code execution path exits the current scope.Example: In this example, if @Cleanup annotation is removed it would be a resource leak.
package com.stackstalk; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.Scanner; import lombok.Cleanup; public class CleanupTest { public static void main(String[] args) throws IOException { InputStream fis = new FileInputStream("/tmp/input.txt"); InputStreamReader reader = new InputStreamReader(fis, StandardCharsets.UTF_8); @Cleanup Scanner in = new Scanner(reader); while ( in.hasNextLine() ) { System.out.println(in.nextLine()); } } }
@Log
Purpose: @Log on class initializes a static final log field, which can be used to write log statements. There are multiple variants for different logging frameworks. (@Log4j2, @Sfl4j).Example: In this example we use the insurance info data class and work with log statements.
package com.stackstalk; import lombok.extern.java.Log; @Log public class DataTest { public static void main(String[] args) { InsuranceInfo insurance1 = new InsuranceInfo("Travel Insurance", 1000, 30000, "Easy"); System.out.println(insurance1); InsuranceInfo insurance2 = new InsuranceInfo("Car Insurance", 2000, 50000, "Moderate"); System.out.println(insurance2); log.info("Created the insurance types"); if (insurance1 == insurance2 ) System.out.println("Same insurance"); else { System.out.println("Different insurance"); log.severe("Different insurance"); } } }
0 comments:
Post a Comment