8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

@Builder(Lombok)の使い方

Last updated at Posted at 2020-03-05

#Lombokの@Builderアノテーションとは?

  • JavaのClassに@Builderを付与することで、Builderメソッドを生成してくれる。
  • 引数のながーいコンストラクターを用意しなくてすむ。
import lombok.Builder;

//呼び出される側のJavaClass
@Builder
public class Employee {
	private String name;
	private int syainId;
	private int age;
	private String position;
	private String status;
}
//Builderを呼び出す側
Employee employee = Employee.builder()
        .name("Kohei Sato")
        .syainId(101)
        .age(32)
        .position("developper")
        .build();

#初期値は??
上記の例では、statusを指定していない。→ statusはnullになってしまう。
Stringなのでnullになっているが、intは0, booleanはfalseになるっぽい。

#初期値の指定方法1:内部クラス

  • 以下の通り,ClassName+Builderのクラスで、デフォルト値を指定可能
@Builder
public class Employee {
    private String name;
    private int syainId;
    private int age;
    private String position;
    private String status;
    
    public static class EmployeeBuilder {
    	private String status = "Active";
    }
}

#初期値の指定方法2:Defaultアノテーションを利用

  • アノテーション付与で変数宣言時に初期値を指定可能。
@Builder
public class Employee {
	@Builder.Default private String name = "No Name";
	@Builder.Default private int syainId = 0;
	@Builder.Default private int age = 30;
	@Builder.Default private String position = "Normal";
	@Builder.Default private String status = "Active";
}

こっちの方が個人的に見やすい。

参考

8
5
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
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?