Lombok使用讲解
简介
Lombok 是一款好用顺手的工具,就像 Google Guava 一样。可用来帮助开发人员消除 Java 的冗长代码,尤其是对于简单的 Java 对象(POJO)。它通过注释实现这一目的。
通过在开发环境中实现 Lombok,开发人员可以节省构建诸如hashCode()和equals()这样的方法以及以往用来分类各种 accessor 和 mutator 的大量时间。
导入 lombok 包
1implementation "org.projectlombok:lombok"
Lombok 注解大全说明
1val:用在局部变量前面,相当于将变量声明为 final
2@NonNull:给方法参数增加这个注解,会自动在方法内对该参数进行是否为空的校验,如果为空,则抛出 NPE(NullPointerException)
3@Cleanup:自动管理资源,用在局部变量之前,在当前变量范围内即将执行完毕退出之前会自动清理资源,自动生成 try-finally 这样的代码来关闭流
4@Getter/@Setter:用在属性上,再也不用自己手写 setter 和 getter 方法了,还可以指定访问范围
5@ToString:用在类上,可以自动覆写 toString 方法,当然还可以加其他参数,例如@ToString(exclude=”id”)排除 id 属性,或者@ToString(callSuper=true, includeFieldNames=true)调用父类的 toString 方法,包含所有属性
6@EqualsAndHashCode:用在类上,自动生成 equals 方法和 hashCode 方法
7@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor:用在类上,自动生成无参构造和使用所有参数的构造函数以及把所有@NonNull 属性作为参数的构造函数,如果指定 staticName = “of”参数,同时还会生成一个返回类对象的静态工厂方法,比使用构造函数方便很多
8@Data:注解在类上,相当于同时使用了@ToString、@EqualsAndHashCod- e、@Getter、@Setter 和@RequiredArgsConstrutor 这些注解,对于 POJO 类十分有用
9@Value:用在类上,是@Data 的不可变形式,相当于为属性添加 final 声明,只提供 getter 方法,而不提供 setter 方法
10@Builder:用在类、构造器、方法上,为你提供复杂的 builder APIs,让你可以像如下方式一样调用 Person.builder().name("Adam Savage").city("San Francisco").job("Mythbusters").job("Unchained Reaction").build();更多说明参考 Builder
11@SneakyThrows:自动抛受检异常,而无需显式在方法上使用 throws 语句
12@Synchronized:用在方法上,将方法声明为同步的,并自动加锁,而锁对象是一个私有的属性 LOCK,而 java 中的 synchronized 关键字锁对象是 this,锁在 this 或者自己的类对象上存在副作用,就是你不能阻止非受控代码去锁 this 或者类对象,这可能会导致竞争条件或者其它线程错误
13@Getter(lazy=true):可以替代经典的 Double Check Lock 样板代码
14@Log:根据不同的注解生成不同类型的 log 对象,但是实例名称都是 log,有六种可选实现类
15@CommonsLog Creates log = org.apache.commons.logging.LogFactory.getLog(LogExample.class);
16@Log Creates log = java.util.logging.Logger.getLogger(LogExample.class.getName());
17@Log4j Creates log = org.apache.log4j.Logger.getLogger(LogExample.class);
18@Log4j2 Creates log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class);
19@Slf4j Creates log = org.slf4j.LoggerFactory.getLogger(LogExample.class);
20@XSlf4j Creates log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);
Lombok 代码示例
val 示例
1public static void main(String[] args) {
2 val sets = new HashSet<String>();
3 val lists = new ArrayList<String>();
4 val maps = new HashMap<String, String>();
5 //=>相当于如下
6 final Set<String> sets2 = new HashSet<>();
7 final List<String> lists2 = new ArrayList<>();
8 final Map<String, String> maps2 = new HashMap<>();
9}
@NonNull 示例
1public void notNullExample(@NonNull String string) {
2 string.length();
3}
4//=>相当于
5public void notNullExample(String string) {
6 if (string != null) {
7 string.length();
8 } else {
9 throw new NullPointerException("null");
10 }
11}
@Cleanup 示例
1public static void main(String[] args) {
2 try {
3 @Cleanup InputStream inputStream = new FileInputStream(args[0]);
4 } catch (FileNotFoundException e) {
5 e.printStackTrace();
6 }
7 //=>相当于
8 InputStream inputStream = null;
9 try {
10 inputStream = new FileInputStream(args[0]);
11 } catch (FileNotFoundException e) {
12 e.printStackTrace();
13 } finally {
14 if (inputStream != null) {
15 try {
16 inputStream.close();
17 } catch (IOException e) {
18 e.printStackTrace();
19 }
20 }
21 }
22}
@Getter/@Setter 示例
1@Setter(AccessLevel.PUBLIC)
2@Getter(AccessLevel.PROTECTED)
3private int id;
4private String shap;
@ToString 示例
1@ToString(exclude = "id", callSuper = true, includeFieldNames = true)
2public class LombokDemo {
3 private int id;
4 private String name;
5 private int age;
6 public static void main(String[] args) {
7 //输出LombokDemo(super=LombokDemo@48524010, name=null, age=0)
8 System.out.println(new LombokDemo());
9 }
10}
@EqualsAndHashCode 示例
1@EqualsAndHashCode(exclude = {"id", "shape"}, callSuper = false)
2public class LombokDemo {
3 private int id;
4 private String shap;
5}
@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor 示例
1@NoArgsConstructor
2@RequiredArgsConstructor(staticName = "of")
3@AllArgsConstructor
4public class LombokDemo {
5 @NonNull
6 private int id;
7 @NonNull
8 private String shap;
9 private int age;
10 public static void main(String[] args) {
11 new LombokDemo(1, "circle");
12 //使用静态工厂方法
13 LombokDemo.of(2, "circle");
14 //无参构造
15 new LombokDemo();
16 //包含所有参数
17 new LombokDemo(1, "circle", 2);
18 }
19}
@Data 示例
1import lombok.Data;
2@Data
3public class Menu {
4 private String shopId;
5 private String skuMenuId;
6 private String skuName;
7 private String normalizeSkuName;
8 private String dishMenuId;
9 private String dishName;
10 private String dishNum;
11 //默认阈值
12 private float thresHold = 0;
13 //新阈值
14 private float newThresHold = 0;
15 //总得分
16 private float totalScore = 0;
17}
@Value 示例
1@Value
2public class LombokDemo {
3 @NonNull
4 private int id;
5 @NonNull
6 private String shap;
7 private int age;
8 //相当于
9 private final int id;
10 public int getId() {
11 return this.id;
12 }
13 ...
14}
@Builder 示例
1@Builder
2public class BuilderExample {
3 private String name;
4 private int age;
5 @Singular
6 private Set<String> occupations;
7 public static void main(String[] args) {
8 BuilderExample test = BuilderExample.builder().age(11).name("test").build();
9 }
10}
@SneakyThrows 示例
1import lombok.SneakyThrows;
2import java.io.FileInputStream;
3import java.io.FileNotFoundException;
4import java.io.InputStream;
5import java.io.UnsupportedEncodingException;
6public class Test {
7 @SneakyThrows()
8 public void read() {
9 InputStream inputStream = new FileInputStream("");
10 }
11 @SneakyThrows
12 public void write() {
13 throw new UnsupportedEncodingException();
14 }
15 //相当于
16 public void read() throws FileNotFoundException {
17 InputStream inputStream = new FileInputStream("");
18 }
19 public void write() throws UnsupportedEncodingException {
20 throw new UnsupportedEncodingException();
21 }
22}
@Synchronized 示例
1public class SynchronizedDemo {
2 @Synchronized
3 public static void hello() {
4 System.out.println("world");
5 }
6 //相当于
7 private static final Object $LOCK = new Object[0];
8 public static void hello() {
9 synchronized ($LOCK) {
10 System.out.println("world");
11 }
12 }
13}
@Getter(lazy = true)
1public class GetterLazyExample {
2 @Getter(lazy = true)
3 private final double[] cached = expensive();
4 private double[] expensive() {
5 double[] result = new double[1000000];
6 for (int i = 0; i < result.length; i++) {
7 result[i] = Math.asin(i);
8 }
9 return result;
10 }
11}
12
13// 相当于如下所示:
14
15import java.util.concurrent.atomic.AtomicReference;
16public class GetterLazyExample {
17 private final AtomicReference<java.lang.Object> cached = new AtomicReference<>();
18 public double[] getCached() {
19 java.lang.Object value = this.cached.get();
20 if (value == null) {
21 synchronized (this.cached) {
22 value = this.cached.get();
23 if (value == null) {
24 final double[] actualValue = expensive();
25 value = actualValue == null ? this.cached : actualValue;
26 this.cached.set(value);
27 }
28 }
29 }
30 return (double[]) (value == this.cached ? null : value);
31 }
32 private double[] expensive() {
33 double[] result = new double[1000000];
34 for (int i = 0; i < result.length; i++) {
35 result[i] = Math.asin(i);
36 }
37 return result;
38 }
39}
发布日期:2023-06-28 20:06 字数:871 用时
标签云
alpine(1) api网关(1) async(1) await(1) centos(4) cli(1) client-go(1) debug(1) docker(10) docker-compose(1) dockerfile(1) embed(1) es6(1) etcd(1) etcdctl(1) freemesh(2) git(6) go(5) go-zeus(5) goland(2) golang(7) grafana(2) grpc(5) grpcurl(1) homebrew(1) homedir(1) http(2) hugo(1) java(2) javascript(3) job(1) js(1) json(1) k8s(16) k8s部署指南(1) kubebuilder(1) kubectl(4) kubernetes(1) linux(2) localecompare(1) lombok(1) metrics(2) mock(1) mysql(1) npm(1) nsenter(1) nvm(1) pnpm(2) pprof(1) prettier(1) prometheus(2) protobuf3(1) protoc(1) qiankun(1) request(1) scss(1) servicemesh(1) spring(1) springcloud->freemesh(1) ssh(2) systemctl(1) tcpdump(1) typescript(2) vite(2) vscode(2) vue(8) vue-admin(2) vue3(1) webssh(1) xtermjs(1) xxl-job(1) yarn(1) zookeeper(1) 云原生(4) 云原生框架(1) 介绍(1) 单体架构->freemesh(1) 单元化(1) 博客(1) 压缩(1) 可观测(1) 后台管理系统(1) 命名规范(1) 多云多活(1) 如水网(1) 安全(1) 安装(1) 容器(2) 开发联调神器(1) 微前端(1) 微服务(2) 微服务架构->freemesh(1) 微服务框架(1) 快速开始(1) 控制面(1) 数据面(1) 文集(2) 服务发现(1) 服务网格(1) 流量泳道(1) 流量管理(1) 监控告警(1) 端口映射(1) 证书(1) 负载均衡(1) 配置(1)