LoginSignup
39
36

More than 5 years have passed since last update.

みんな大好きlombokでimmutableなクラスを簡単に作る等

Last updated at Posted at 2017-02-15

lombokはアクセッサ系のアノテーション(@GET,@SET,@DATA)だけを使っていても十分便利ですが、
@Valueでimmutableなクラスを生成するのはもっと便利です。

lombokなしで、immutableなPairクラスを作ってみます。
コンストラクタは隠蔽して、staticメソッドのofでオブジェクトを生成しています。

public final class ImmutablePair<L, R> {

    public static <L, R> ImmutablePair<L, R> of(L left, R right){
        return new ImmutablePair<>(left, right);
    }

    private ImmutablePair(L left, R right) {
        this.left = left;
        this.right = right;
    }

    private final L left;
    private final R right;

    public L left() {
        return left;
    }

    public R right() {
        return left;
    }

    public ImmutablePair<L, R> right(R r) {
        right = r;
        return this;
    }

    public ImmutablePair<L, R> left(L le) {
        left = le;
        return this;
    }
}

// 生成
ImmutablePair<String, Integer> pair = ImmutablePair.of("name", 10);

。。。面倒ですね。

これをlombokで書くと、たったこんだけです。使わない理由がありませんね。

@Value(staticConstructor="of")
@Accessors(fluent=true)
public final class ImmutablePair<L, R> {
    L left;
    R right;
}

// 生成
ImmutablePair<String, Integer> pair = ImmutablePair.of("name", 10);

フィールドが多いときはビルダーパターンを実現してくれる@Builderを使うといいです。
同じ型のフィールドがあり、コンストラクタでパラメーターの順番を間違えちゃうというありがちな
ミスを防ぐことができます。

@Value
@Accessors(fluent=true)
@Builder
public final class Person {
    String firstName;
    String lastName;
    String email;
    int age ;
}

// こんな感じで使います。
Sample sample = Sample.builder()
                        .firstName("first")
                        .lastName("last")
                        .email("mail@xxxxx.com")
                        .age(18)
                        .build();
39
36
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
39
36