LoginSignup
4
0

More than 1 year has passed since last update.

Lombokの内容整理①

Posted at

目的

  • ずっとなんとなく使っていたので、改めてこのタイミングで整理

Lombokとは

  • アノテーションをつけることでコンパイル時にコードを自動生成してくれるライブラリのこと
  • 今回扱うアノテーション一覧

@Getter/@Setter

概要
  • アクセサメソッドを自動生成
使い方
Person
@Getter
@Setter
public class Person {
  private String name;
}
コンパイル時に自動生成されるコード
public class Person {
  private String name;

  @Generated
  public String getName() {
    return this.name;
  }

  @Generated
  public void setName(final String name) {
    this.name = name;
  }
指定場所 / 用途
  • クラス・フィールドに指定可能
  • フィールド変数にアクセスする場合に設定

@ToString

概要
  • すべてのフィールドを1つの文字列表現に変換するtoStringメソッドを自動生成
使い方
Person
@ToString
public class Person {
  private String name;
}
コンパイル時に自動生成されるコード
public class Person {
  private String name;

  @Generated
  public String toString() {
    return "Person(name=" + this.name + ")";
  }
指定場所 / 用途
  • クラスに指定
  • ログ出力などで使用

@EqualsAndHashCode

概要
  • すべてのフィールドを使用してequalsメソッドとhashCodeメソッドを自動生成
  • equalsメソッドとは
    • Stringの場合:同じ文字列かどうかの比較を行う
    • Objectの場合:オブジェクトが同一かどうかの比較を行う
  • hashCodeメソッドとは
    • 呼び出し元のオブジェクトをハッシュコードと呼ばれるint型の値に変換し、戻り値として返す
    • ※ハッシュコードとはオブジェクトにつけられる一つの整数値で、オブジェクトの一意の識別などに用いられる値
使い方
Person
@EqualsAndHashCode
public class Person {
  private String name;
}
コンパイル時に自動生成されるコード
public class Person {
  private String name;

  public Person() {
  }

  @Generated
  public boolean equals(final Object o) {
    if (o == this) {
      return true;
    } else if (!(o instanceof Person)) {
      return false;
    } else {
      Person other = (Person)o;
      if (!other.canEqual(this)) {
        return false;
      } else {
        Object this$name = this.name;
        Object other$name = other.name;
        if (this$name == null) {
          if (other$name != null) {
            return false;
          }
        } else if (!this$name.equals(other$name)) {
          return false;
        }

        return true;
      }
    }
  }

  @Generated
  protected boolean canEqual(final Object other) {
    return other instanceof Person;
  }

  @Generated
  public int hashCode() {
    int PRIME = true;
    int result = 1;
    Object $name = this.name;
    int result = result * 59 + ($name == null ? 43 : $name.hashCode());
    return result;
  }
}
用途
  • インスタンスの一致確認が必要な場合に設定
4
0
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
4
0