lombok学习记录
lombok安装就用maven下载的jar包, 用java -jar lombok1.16.18.jar打开, 然后选择IDE安装目录即可安装.
API文档: https://projectlombok.org/api/lombok/ToString.html
- @Getter @Setter
@Getter和@Setter
- 访问修饰:AccessLevel.PROTECTED等
ToString
Generates an implementation for the toString method inherited by all objects, consisting of printing the values of relevant fields.
- callSuper
调用父类toString方法 默认false - includeFieldNames
是否带字段名输出, 默认true - exclude
排除字段,多个字段用{“a”, “b”} - of
打印出指定字段列表中的字段 of={“c”, “d”}
@EqualsAndHashCode
This class level annotation will cause Lombok to generate both equals and hashCode methods, as the two are tied together intrinsically by the hashCode contract.
- callSuper
调用父类方法 默认false - exclude
排除字段,多个字段用{“a”, “b”} - of
打印出指定字段列表中的字段 of={“c”, “d”}
@Data
All together now: A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, and @Setter on all non-final fields, and @RequiredArgsConstructor!
- staticConstructor
@Data(staticConstructor = "of")
public class Point
{
final int x, y;
}
用final字段, 调用静态构造方法 Point.of(1,2), 这种情况下, 没有setX和setY方法.
ToString结果: Point(x=1, y=2)
@CleanUp
The @Cleanup annotation can be used to ensure that allocated resources are released. When a local variable is annotated with @Cleanup, any subsequent code is wrapped in a try/finally block that guarantees that the cleanup method is called at the end of the current scope. By default @Cleanup assumes that the cleanup method is named “close”, as with input and output streams. However, a different method name can be provided to the annotation’s value parameter. Only cleanup methods which take no parameters are able to be used with this annotation.
- value
默认值 “close”, 可以指定其他不带参的方法.
@Log4j
- topic
可以给topic指定一个值,如果没有topic, 默认用class的全路径做日志标签
自动添加Log4j日志对象log
程序中直接使用log.info()调用
@Data
@Builder
@Log4j(topic = "TestLog")
public class Point2 {
int x, y;
public static void main(String[] args) {
Point2 pb = Point2.builder().x(1).y(2).build();
log.info(pb);
}
}
输出:
20:23:25.964 [main] INFO TestLog - Point2(x=1, y=2)
如果不指定topic, 输出
20:27:44.604 [main] INFO com.neo.entity.lambok.Point2 - Point2(x=1, y=2)
@Builder
@Builder
class Example {
private int foo;
private final String bar;
}
编译后:
class Example<T> {
private T foo;
private final String bar;
private Example(T foo, String bar) {
this.foo = foo;
this.bar = bar;
}
public static <T> ExampleBuilder<T> builder() {
return new ExampleBuilder<T>();
}
public static class ExampleBuilder<T> {
private T foo;
private String bar;
private ExampleBuilder() {}
public ExampleBuilder foo(T foo) {
this.foo = foo;
return this;
}
public ExampleBuilder bar(String bar) {
this.bar = bar;
return this;
}
@java.lang.Override public String toString() {
return "ExampleBuilder(foo = " + foo + ", bar = " + bar + ")";
}
public Example build() {
return new Example(foo, bar);
}
}
}