はじめに#
普段使っているアノテーションを整理するためにメモに残しとこうと思います。基本的にこちらを引用しています。
コンストラクタ生成タイプのアノテーション#
@NoArgsConstructor#
デフォルトコンストラクタを生成するもの(メンバー変数なし)
1
2
3
4
5
6
7
8
9
10
11
12
| import lombok.NoArgsConstructor;
@NoArgsConstructor
public class Person1 {
private long id;
private String name;
private int age;
// 実際には以下が追加される
public Person1() {
}
}
|
@AllArgsConstructor#
すべてのメンバー変数の値をセットできるコンストラクタが自動で生成される
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| import lombok.AllArgsConstructor;
@AllArgsConstructor
public class Person2 {
private long id;
private String name;
private int age;
// 実際には以下が追加される
public Person2(final long id, final String name, final int age) {
this.id = id;
this.name = name;
this.age = age;
}
}
|
@RequiredArgsConstructor#
すべての final
メンバー変数の値をセットできるコンストラクタが自動で生成される
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
public class Person4 {
private final long id;
private String name;
private int age;
// 実際には以下が追加される
public Person4(final long id) {
this.id = id;
}
}
|
組み合わせパターン#
上記で紹介したアノテーションは組み合わせることが可能
@RequiredArgsConstructor + @AllArgsConstructor#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor
@AllArgsConstructor
public class Person5 {
private final long id;
private String name;
private int age;
// 実際には以下が追加される
public Person5(final long id) {
this.id = id;
}
public Person5(final long id, final String name, final int age) {
this.id = id;
this.name = name;
this.age = age;
}
}
|
@NoArgsConstructor + @AllArgsConstructor#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
@NoArgsConstructor
@AllArgsConstructor
public class Person3 {
private long id;
private String name;
private int age;
// 実際には以下が追加される
public Person3() {}
public Person3(final long id, final String name, final int age) {
this.id = id;
this.name = name;
this.age = age;
}
}
|
その他#
1
2
3
4
5
6
| @RequiredArgsConstructor(access=AccessLevel.PROTECTED)
public static class Person6b {
private final long id;
private String name;
private int age;
}
|
1
2
3
4
5
6
7
| @NoArgsConstructor(staticName="create")
@AllArgsConstructor(staticName="create")
public static class Person7b {
private long id;
private String name;
private int age;
}
|
Person7b.create()
で呼び出すことができる
1
2
3
4
5
6
7
8
9
10
| public class Person8 {
@RequiredArgsConstructor
public static class Person8a {
private long id;
@NonNull
private final String name;
private int age;
}
}
|
以上で null を許容しなくできる
終わりに#
まだまだ色々小技があると思いますが、ひとまずはこれくらいで。
References#