[Java] Boilerplate code elimination using Lombok 2

theme

Continuing from Last time, Lombok introduced the boilerplate function.

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

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

@Builder

Generate source for Builder Patterns

[Lombok annotation source]

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

[Runtime source]

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

    @java.lang.SuppressWarnings("all")
    Builder(final int id, final String name, final int price, final String publishDate) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.publishDate = publishDate;
    }


    @java.lang.SuppressWarnings("all")
    public static class BuilderBuilder {
        @java.lang.SuppressWarnings("all")
        private int id;
        @java.lang.SuppressWarnings("all")
        private String name;
        @java.lang.SuppressWarnings("all")
        private int price;
        @java.lang.SuppressWarnings("all")
        private String publishDate;

        @java.lang.SuppressWarnings("all")
        BuilderBuilder() {
        }

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

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

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

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

        @java.lang.SuppressWarnings("all")
        public Builder build() {
            return new Builder(id, name, price, publishDate);
        }

        @java.lang.Override
        @java.lang.SuppressWarnings("all")
        public java.lang.String toString() {
            return "Builder.BuilderBuilder(id=" + this.id + ", name=" + this.name + ", price=" + this.price + ", publishDate=" + this.publishDate + ")";
        }
    }

    @java.lang.SuppressWarnings("all")
    public static BuilderBuilder builder() {
        return new BuilderBuilder();
    }
}

[How to use]

public class Main {
    public static void main(String... args){
        System.out.println(
                Builder.builder()
                        .id(100)
                        .name("name")
                        .price(937)
                        .publishDate("2018-11-09")
                        .build().toString());
    }
}

@Value

Generate immutable class

[Lombok annotation source]

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

[Runtime source]

public final class Value {
    private final int id;
    private final String name;
    private final int price;
    private final String publishDate;

    @java.lang.SuppressWarnings("all")
    public Value(final int id, final String name, final int price, final String publishDate) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.publishDate = publishDate;
    }

    @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.Override
    @java.lang.SuppressWarnings("all")
    public boolean equals(final java.lang.Object o) {
        if (o == this) return true;
        if (!(o instanceof Value)) return false;
        final Value other = (Value) o;
        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.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 "Value(id=" + this.getId() + ", name=" + this.getName() + ", price=" + this.getPrice() + ", publishDate=" + this.getPublishDate() + ")";
    }
}

@Cleanup

It adds closing logic after processing such as file opening. However, if you are using Java 7 or later, you should use try-with-resources, so if you use it, maybe up to Java 6.

public class Cleanup {
    public static void main(String[] args) throws IOException {
        @lombok.Cleanup InputStream in = new FileInputStream(args[0]);
        @lombok.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);
        }
    }
}
import java.io.*;

public class Cleanup {
    public static void main(String[] args) throws IOException {
        InputStream in = new FileInputStream(args[0]);
        try {
            OutputStream out = new FileOutputStream(args[1]);
            try {
                byte[] b = new byte[10000];
                while (true) {
                    int r = in.read(b);
                    if (r == -1) break;
                    out.write(b, 0, r);
                }
            } finally {
                if (java.util.Collections.singletonList(out).get(0) != null) {
                    out.close();
                }
            }
        } finally {
            if (java.util.Collections.singletonList(in).get(0) != null) {
                in.close();
            }
        }
    }
}

@Log (java.util.logger.Logger)

[Lombok annotation source]

@lombok.extern.java.Log
public class LogExample {
    public static void main(String... args) {
        log.severe("Something's wrong here");
    }
}

[Runtime source]

public class LogExample {
    @java.lang.SuppressWarnings("all")
    private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName());

    public static void main(String... args) {
        log.severe("Something\'s wrong here");
    }
}

@NonNull

Insert null check for method argument. However, by default NullPointerException is thrown. It is possible to change it to ʻIllegalArgumentException`.

[Lombok annotation source]

public class NonNull {
    private int id;
    @lombok.NonNull
    private String name;

    public void setNonNull(@lombok.NonNull Book book) {
        this.name = book.getName();
    }
}

[Runtime source]

public class NonNull {
    private int id;
    @lombok.NonNull
    private String name;

    public void setNonNull(@lombok.NonNull Book book) {
        if (book == null) {
            throw new java.lang.NullPointerException("book is marked @NonNull but is null");
        }
        this.name = book.getName();
    }
}

Summary

For the time being, I picked up and introduced some of the basic functions. By the way, the head family is ↓ https://projectlombok.org/features/all

Other experimental features are introduced below. https://projectlombok.org/features/experimental/all

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
Getting started with Java programs using Visual Studio 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
Try using RocksDB in Java
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