This is the 17th day of my participation in the More text Challenge. For more details, see more text Challenge
Welcome to read: New Dads, Advancing on technology | Mid-2021 summary
Introduction to Lombok
Lombok can simplify Java code in the form of simple annotations, making developers more productive. For example, the development of javabeans often need to write, need to spend time to add the corresponding getter/setter, maybe write constructors, equals, etc., and need to maintain, when there are many properties there will bea lot of getter/setter methods, these are very verbose and not very technical. Once a property is modified, it is easy to make the mistake of forgetting to modify the corresponding method.
Lombok automatically generates constructors, getters/setters, equals, HashCode, and toString methods for properties through annotations at compile time. The magic is that there are no getters and setters in the source code, but there are getters and setters in the compiled bytecode file. This saves you the trouble of manually rebuilding the code and makes it look cleaner.
The use of Lombok like quote jars, can be downloaded in’s official website (projectlombok.org/download)…
<! -- Lombok dependency --><dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.10</version>
<scope>provided</scope>
</dependency>
Copy the code
Two, commonly used annotations
- The @data annotation on a class automatically generates setter/getter, equals, canEqual, hashCode, and toString methods for all properties of the class. If the property is final, the setter method is not generated for the property.
import lombok.AccessLevel;
import lombok.Setter;
import lombok.Data;
import lombok.ToString;
@Data
public class DataExample {
private final String name;
@Setter(AccessLevel.PACKAGE) private int age;
private double score;
private String[] tags;
@ToString(includeFieldNames=true)
@Data(staticConstructor="of")
public static class Exercise<T> {
private final Stringname; private final T value; }}Copy the code
- @Getter/ @setter if @data is too harsh (because @Data aggregates all the features of @toString, @EqualSandHashCode, @getter / @setter, and @requiredargsConstructor) it’s not fine enough You can use the @getter / @setter annotation, which automatically generates Getter/Setter methods on a property for the corresponding property.
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
public class GetterSetterExample {
@Getter @Setter
private int age = 10;
@Setter(AccessLevel.PROTECTED)
private String name;
@Override public String toString() {
return String.format("%s (age: %d)", name, age); }}Copy the code
- NonNull This annotation is used on attributes or constructors. Lombok generates a non-null declaration that can be used to validate parameters and can help avoid null Pointers.
import lombok.NonNull;
public class NonNullExample extends Something {
private String name;
public NonNullExample(@NonNull Person person) {
super("Hello");
this.name = person.getName(); }}Copy the code
- This annotation helps us automatically call the close() method, simplifying the code a lot.
import lombok.Cleanup;
import java.io.*;
public class CleanupExample {
public static void main(String[] args) throws IOException {
@Cleanup
InputStream in = new FileInputStream(args[0]);
@Cleanup
OutputStream out = new FileOutputStream(args[1]);
byte[] b = new byte[10000];
while (true) {
int r = in.read(b);
if (r == -1) break;
out.write(b, 0, r); }}}Copy the code
- @EqualSandHashCode by default generates equals and hasCode using all non-static and non-transient attributes, and excludes some attributes by exclude.
import lombok.EqualsAndHashCode;
@EqualsAndHashCode
public class EqualsAndHashCodeExample {
private transient int transientVar = 10;
private String name;
private double score;
@EqualsAndHashCode.Exclude
private Shape shape = new Square(5.10);
private String[] tags;
@EqualsAndHashCode.Exclude
private int id;
public String getName() {
return this.name;
}
@EqualsAndHashCode(callSuper=true)
public static class Square extends Shape {
private final int width, height;
public Square(int width, int height) {
this.width = width;
this.height = height; }}}Copy the code
- The @toString class uses the @toString annotation, and Lombok generates a ToString () method that, by default, prints the class name, all attributes (in the order they were defined), separated by commas. By setting the includeFieldNames parameter to true, you can explicitly output the toString() attribute. This is a bit of a mouthful, but it will be clearer in the code.
import lombok.ToString;
@ToString
public class ToStringExample {
private static final int STATIC_VAR = 10;
private String name;
private Shape shape = new Square(5.10);
private String[] tags;
@ToString.Exclude private int id;
public String getName() {
return this.name;
}
@ToString(callSuper=true, includeFieldNames=true)
public static class Square extends Shape {
private final int width, height;
public Square(int width, int height) {
this.width = width;
this.height = height; }}}Copy the code
- @noargsConstructor, @requiredargsConstructor and @AllargsConstructor take no, partial, or full arguments. Lombok does not allow multiple parameter constructors to be overloaded.
import lombok.AccessLevel;
import lombok.RequiredArgsConstructor;
import lombok.AllArgsConstructor;
import lombok.NonNull;
@RequiredArgsConstructor(staticName = "of")
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class ConstructorExample<T> {
private int x, y;
@NonNull private T description;
@NoArgsConstructor
public static class NoArgsExample {
@NonNull private Stringfield; }}Copy the code
Three, advantages and disadvantages
Advantages:
1, can automatically generate the constructor, getter/setter, equals, hashcode, toString and other methods through the annotation form, improve the development efficiency.
2. Keep the code simple, and don’t focus too much on methods.
3. When properties are modified, it is also easier to maintain getter/setter methods generated for those properties.
Disadvantages:
1. Overloading of multiple parameter constructors is not supported.
2. Although it saves the trouble of manually creating getter/setter methods, it greatly reduces the readability and integrity of source code, and reduces the comfort of reading source code.
Iv. Official documents
For more information on the official documentation, click Lombok Introduction. Thank you for reading.
Recommended column:
Build a personal tech blog from scratch
Java full stack Architect
Spring Cloud series