转载自: https://blog.csdn.net/mccand1234/article/details/53456411
常用的 lombok 注解
@EqualsAndHashCode:实现equals()方法和hashCode()方法 @ToString:实现toString()方法
@Data :注解在类上;提供类所有属性的 getting 和 setting 方法,此外还提供了equals、canEqual、hashCode、toString 方法
@Setter:注解在属性上;为属性提供 setting 方法
@Getter:注解在属性上;为属性提供 getting 方法
@Log4j :注解在类上;为类提供一个 属性名为log 的 log4j 日志对象
@NoArgsConstructor:注解在类上;为类提供一个无参的构造方法
@AllArgsConstructor:注解在类上;为类提供一个全参的构造方法
@Cleanup:关闭流 @Synchronized:对象同步 @SneakyThrows:抛出异常
publicclassPerson {privateString id;privateString name;privateString identity;privateLogger log = Logger.getLogger(Person.class);publicPerson() { }publicPerson(String id, String name, String identity) {this.id = id;this.name = name;this.identity = identity; }publicStringgetId() {returnid; }publicStringgetName() {returnname; }publicStringgetIdentity() {returnidentity; }publicvoidsetId(String id) {this.id = id; }publicvoidsetName(String name) {this.name = name; }publicvoidsetIdentity(String identity) {this.identity = identity; }}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
@Data@Log4j@NoArgsConstructor@AllArgsConstructorpublicclassPerson{privateString id;privateString name;privateString identity;}
1
2
3
4
5
6
7
8
9
上面的两个 java 类,从作用上来看,它们的效果是一样的,相比较之下,很明显,使用 lombok 要简洁许多
org.projectlomboklombok
1
2
3
4
publicclassExample {privateT foo;privatefinal String bar;privateExample(T foo, String bar) {this.foo = foo;this.bar = bar; }publicstatic ExampleBuilderbuilder() {returnnewExampleBuilder(); }publicstaticclassExampleBuilder {privateT foo;privateString bar;privateExampleBuilder() {}publicExampleBuilderfoo(T foo) {this.foo = foo;returnthis; }publicExampleBuilderbar(String bar) {this.bar = bar;returnthis; } @java.lang.OverridepublicStringtoString() {return"ExampleBuilder(foo = "+ foo +", bar = "+ bar +")"; }publicExamplebuild() {returnnewExample(foo, bar); } } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@BuilderpublicclassExample{privateintfoo;privatefinalString bar; }
1
2
3
4
5
构造一个实例,属性不需要单独set
Example.builder().foo(1).bar(“test”).build()
参考:
http://projectlombok.org/features/index.
http://blog.csdn.net/hack8/article/details/23790579
http://blog.csdn.net/ethanq/article/details/7185610 [builder模式设计]
个人分类: java
网友评论