[Java] Boilerplate code elimination using Lombok

theme

In Java, for example, if you create so-called JavaBeans like ↓, the amount of code will be quite large depending on the number of fields.

public class Book {
    private int id;
    private String name;
    private int price;
    private String publishDate;

    public Book() {
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public String getPublishDate() {
        return publishDate;
    }

    public void setPublishDate(String publishDate) {
        this.publishDate = publishDate;
    }

    @Override
    public String toString() {
        return "Book{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", publishDate='" + publishDate + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Book book = (Book) o;
        return id == book.id &&
                price == book.price &&
                Objects.equals(name, book.name) &&
                Objects.equals(publishDate, book.publishDate);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, price, publishDate);
    }
}

If you use Lombok, this will be the code that has the same method as ↑ just by writing like ↓.

import lombok.Data;

@Data
public class Book {
    private int id;
    private String name;
    private int price;
    private String publishDate;
}

It's convenient, so I'll look into it a little.

Development environment

OS

$ cat /etc/os-release 
NAME="Ubuntu"
VERSION="17.10 (Artful Aardvark)"

Java

$ java -version
java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)

IDE

Everyone loves IntelliJ IDEA

Practice

Installation procedure

Maven project generation

mvn -B archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=com.example -DartifactId=try-java-lombok

Added Lombok to pom.xml

  <dependencies>
     〜〜〜
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.4</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

Added Lombok plugin to IntelliJ

001.png

Download Jar to see what the code looks like with Lombok

https://projectlombok.org/download

Try each annotation

All sources are ↓ https://github.com/sky0621/try-java-lombok

@ Getter and @ Setter

As the name suggests, a getter setter is automatically generated when it is added to a variable.

[Lombok annotation source]

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class GetterSetter {
    private String text;
}

[Runtime source]

public class GetterSetter {
    private String text;

    @java.lang.SuppressWarnings("all")
    public String getText() {
        return this.text;
    }

    @java.lang.SuppressWarnings("all")
    public void setText(final String text) {
        this.text = text;
    }
}

@ToString

as its name suggests.

[Lombok annotation source]

@lombok.ToString
public class ToString {
    private String text;
}

[Runtime source]

public class ToString {
    private String text;

    @java.lang.Override
    @java.lang.SuppressWarnings("all")
    public java.lang.String toString() {
        return "ToString(text=" + this.text + ")";
    }
}

@EqualsAndHashCode

Generate "equals" method and "hashCode" method.

[Lombok annotation source]

@lombok.EqualsAndHashCode
public class EqualsAndHashCode {
    private String text;
}

[Runtime source]

public class EqualsAndHashCode {
    private String text;

    @java.lang.Override
    @java.lang.SuppressWarnings("all")
    public boolean equals(final java.lang.Object o) {
        if (o == this) return true;
        if (!(o instanceof EqualsAndHashCode)) return false;
        final EqualsAndHashCode other = (EqualsAndHashCode) o;
        if (!other.canEqual((java.lang.Object) this)) return false;
        final java.lang.Object this$text = this.text;
        final java.lang.Object other$text = other.text;
        if (this$text == null ? other$text != null : !this$text.equals(other$text)) return false;
        return true;
    }

    @java.lang.SuppressWarnings("all")
    protected boolean canEqual(final java.lang.Object other) {
        return other instanceof EqualsAndHashCode;
    }

    @java.lang.Override
    @java.lang.SuppressWarnings("all")
    public int hashCode() {
        final int PRIME = 59;
        int result = 1;
        final java.lang.Object $text = this.text;
        result = result * PRIME + ($text == null ? 43 : $text.hashCode());
        return result;
    }
}

@NoArgsConstructor

Generate a no-argument constructor

[Lombok annotation source]

@lombok.NoArgsConstructor
public class NoArgsConstructor {
}

[Runtime source]

public class NoArgsConstructor {
	@java.lang.SuppressWarnings("all")
	public NoArgsConstructor() {
	}
}

@AllArgsConstructor

Generate a constructor with all arguments

[Lombok annotation source]

@lombok.AllArgsConstructor
public class AllArgsConstructor {
    private int id;
    private String name;
    private Date created;
}

[Runtime source]

public class AllArgsConstructor {
    private int id;
    private String name;
    private Date created;

    @java.lang.SuppressWarnings("all")
    public AllArgsConstructor(final int id, final String name, final Date created) {
        this.id = id;
        this.name = name;
        this.created = created;
    }
}

@RequiredArgsConstructor

Generate a constructor with one parameter for each field that requires special processing

[Lombok annotation source]

@lombok.RequiredArgsConstructor
public class RequiredArgsConstructor {
    @NonNull
    private int id;

    @NonNull
    private String text;

    private Data created;
}

[Runtime source]

import lombok.Data;
import lombok.NonNull;

public class RequiredArgsConstructor {
    @NonNull
    private int id;
    @NonNull
    private String text;
    private Data created;

    @java.lang.SuppressWarnings("all")
    public RequiredArgsConstructor(@NonNull final int id, @NonNull final String text) {
        if (text == null) {
            throw new java.lang.NullPointerException("text is marked @NonNull but is null");
        }
        this.id = id;
        this.text = text;
    }
}

@Data

Of the annotations introduced above, @ToString, @EqualsAndHashCode, and @ Getter are added to all fields, and @Setter is added to all final fields. Also, @RequiredArgsConstructor is added.

[Lombok annotation source]

@lombok.Data
public class Data {
    private int id;
    private String name;
    private int price;
    private String publishDate;
}

[Runtime source]

public class Data {
    private int id;
    private String name;
    private int price;
    private String publishDate;

    @java.lang.SuppressWarnings("all")
    public Data() {
    }

    @java.lang.SuppressWarnings("all")
    public int getId() {
        return this.id;
    }

    @java.lang.SuppressWarnings("all")
    public String getName() {
        return this.name;
    }

    @java.lang.SuppressWarnings("all")
    public int getPrice() {
        return this.price;
    }

    @java.lang.SuppressWarnings("all")
    public String getPublishDate() {
        return this.publishDate;
    }

    @java.lang.SuppressWarnings("all")
    public void setId(final int id) {
        this.id = id;
    }

    @java.lang.SuppressWarnings("all")
    public void setName(final String name) {
        this.name = name;
    }

    @java.lang.SuppressWarnings("all")
    public void setPrice(final int price) {
        this.price = price;
    }

    @java.lang.SuppressWarnings("all")
    public void setPublishDate(final String publishDate) {
        this.publishDate = publishDate;
    }

    @java.lang.Override
    @java.lang.SuppressWarnings("all")
    public boolean equals(final java.lang.Object o) {
        if (o == this) return true;
        if (!(o instanceof Data)) return false;
        final Data other = (Data) o;
        if (!other.canEqual((java.lang.Object) this)) return false;
        if (this.getId() != other.getId()) return false;
        final java.lang.Object this$name = this.getName();
        final java.lang.Object other$name = other.getName();
        if (this$name == null ? other$name != null : !this$name.equals(other$name)) return false;
        if (this.getPrice() != other.getPrice()) return false;
        final java.lang.Object this$publishDate = this.getPublishDate();
        final java.lang.Object other$publishDate = other.getPublishDate();
        if (this$publishDate == null ? other$publishDate != null : !this$publishDate.equals(other$publishDate)) return false;
        return true;
    }

    @java.lang.SuppressWarnings("all")
    protected boolean canEqual(final java.lang.Object other) {
        return other instanceof Data;
    }

    @java.lang.Override
    @java.lang.SuppressWarnings("all")
    public int hashCode() {
        final int PRIME = 59;
        int result = 1;
        result = result * PRIME + this.getId();
        final java.lang.Object $name = this.getName();
        result = result * PRIME + ($name == null ? 43 : $name.hashCode());
        result = result * PRIME + this.getPrice();
        final java.lang.Object $publishDate = this.getPublishDate();
        result = result * PRIME + ($publishDate == null ? 43 : $publishDate.hashCode());
        return result;
    }

    @java.lang.Override
    @java.lang.SuppressWarnings("all")
    public java.lang.String toString() {
        return "Data(id=" + this.getId() + ", name=" + this.getName() + ", price=" + this.getPrice() + ", publishDate=" + this.getPublishDate() + ")";
    }
}

Summary

There are still useful annotations, but today is out of time. The rest will come later.

Recommended Posts

[Java] Boilerplate code elimination using Lombok
[Java] Boilerplate code elimination using Lombok 2
Sample code using Minio from Java
Script Java code
Java code TIPS
Java sample code 02
Java sample code 03
Java sample code 04
Java sample code 01
Java character code
[Java] Convert DB code to code value using enum
Try using Sourcetrail (win version) in Java code
Try using Sourcetrail (macOS version) in Java code
Using Gradle with VS Code, build Java → run
Write Selenium Java binding code using Silk WebDriver
Sorting using java comparator
Lombok with VS Code
Scraping practice using Java ②
Scraping practice using Java ①
Differences in code when using the length system in Java
Create QR code for Google Authenticator using ZXing in Java
Talk about using Java input wait (Scanner) in VS Code
Digital signature sample code (JAVA)
Java parallelization code sample collection
Try scraping using java [Notes]
Java test code method collection
[Windows] Java code is garbled
[Rails] Test code using Rspec
Using Mapper with Java (Spring)
Java in Visual Studio Code
Write Java8-like code in Java8
I tried using Java REPL
Reduce verbose code with Lombok
Using Docker from Java Gradle
Make a rhombus using Java
Bubble sort using ArrayList (JAVA)
Avoid character code error in java when using VScode extension RUN-CODE