简介
- 简化POJO神器。
1. @Getter 和 @Setter
- 例子:
public class Test1 {
@Getter
@Setter
private int age = 10;
@Getter
@Setter
private boolean active; //isActive()、setActive()
@Getter
@Setter
private Boolean none;
@Getter
@Setter
private Date date;
@Setter(AccessLevel.PROTECTED)
private String name;
@Override
public String toString() {
return String.format("%s (age: %d)", name, age);
}
public static void main(String[] args) {
Test1 t = new Test1();
t.setActive(true);
t.setAge(123);
t.setDate(new Date());
t.setName("abc");
t.setNone(false);
Date date = t.getDate();
Boolean none = t.getNone();
boolean active = t.isActive();
}
}
2. @ToString
- 例子
@Setter
@ToString(exclude="id")
public class Test2 {
private static final int STATIC_VAR = 10;
private String name;
private Shape shape = new Square(5, 10);
@ToString(callSuper=true, includeFieldNames=true)
public static class Square extends Shape {
private final int width, height;
public Square(int width, int height) {
this.width = width;
this.height = height;
}
}
@ToString
public static class Shape {
private int color;
}
public static void main(String[] args) {
final Test2 example = new Test2();
example.setId(1);
example.setName("abc");
final Shape shape = new Square(1,2);
example.setShape(shape);
System.out.println(example.toString());
}
}
注意:
- callSuper为true,可以将超类实现toString的输出包含到输出中
3. @EqualsAndHashCode
- 例子
@EqualsAndHashCode(exclude={"id", "shape"})
public class Test3 {
private transient int transientVar = 10;
private String name;
private double score;
private Test3.Shape shape = new Square(5, 10);
private int id;
public String getName() {
return this.name;
}
@EqualsAndHashCode(callSuper=true)
public static class Square extends ToStringExample.Shape {
private final int width, height;
public Square(int width, int height) {
this.width = width;
this.height = height;
}
}
public static void main(String[] args) {
Test3 example = new Test3();
Test3 example1 = new Test3();
boolean equals = example.equals(example1);
boolean b = example.canEqual(example);
int i = example.hashCode();
}
}
4. @NoArgsConstructor、@RequiredArgsConstructor、@AllArgsConstructor
- 例子:
@NoArgsConstructor
public static class Test4 {
@NonNull private String field;
}
/**
* 对于关注的字段标注@NonNull, @RequiredArgsConstructor则会生成带有这些字段,不包含没有@NonNull注解的字段的构造器。
*/
@RequiredArgsConstructor
public class RequiredArgsExample {
@NonNull private String field;
private Date date;
private int i;
private boolean b;
}
@AllArgsConstructor(access = AccessLevel.PROTECTED)
public class ConstructorExample<T> {
private int x, y;
@NonNull
private T description;
}
5. 必须项@Data
- @Data是一个集合体。包含Getter,Setter,RequiredArgsConstructor,ToString,EqualsAndHashCode
6. 不可变对象@Value
- 所有的字段都将生成final的
- @Value是一个集合体。包含Getter,AllArgsConstructor,ToString,EqualsAndHashCode。
7. @Builder 建造者
- 此处省略,具体开发中很少用到。
8. @Slf4j
- @Slf4j 注解在类,生成log变量,严格意义来说是常量。相当于:
private static final Logger log = LoggerFactory.getLogger(UserController.class);
QA
- 1.详细了解,请点击这里