Lombok快速上手(安装、使用与注解参数)
Lombok插件安装与使用说明
在实习中发现项目中IDE一直报检查错误,原来是使用了Lombok注解的黑科技,这里整理了一些日常编码中能遇到的所有关于它的使用详解,其实lombok项目的产生就是为了省去我们手动创建getter和setter方法等等一些基本组件代码的麻烦,它能够在我们编译源码的时候自动帮我们生成getter和setter方法。即它最终能够达到的效果是:在源码中没有getter和setter等组件方法,但是在编译生成的字节码文件中有getter和setter等组件方法。
常见参数
- @Setter 注解在类或字段,注解在类时为所有字段生成setter方法,注解在字段上时只为该字段生成setter方法。
- @Getter 使用方法同上,区别在于生成的是getter方法。
- @ToString 注解在类,添加toString方法。
- @EqualsAndHashCode 注解在类,生成hashCode和equals方法。
- @NoArgsConstructor 注解在类,生成无参的构造方法。
- @RequiredArgsConstructor 注解在类,为类中需要特殊处理的字段生成构造方法,比如final和被@NonNull注解的字段。
- @AllArgsConstructor 注解在类,生成包含类中所有字段的构造方法。
- @Data 注解在类,为类的所有字段注解@ToString、@EqualsAndHashCode、@Getter的便捷方法,同时为所有非final字段注解@Setter。
lombok的依赖于安装
依赖管理
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
</dependency>
IDEA插件的安装
如果IDE没有安装插件的话会提示错误,而且不会有代码提示,所以IDE要安装插件
- 在IDEA插件里搜索lombok,安装,重启
- 直接官网下载插件,安装,这是链接
- 设置中启用annotation processors
@Data小例子
平时在使用时最常用@Data注解
@Data可以很好地处理字段的泛型参数。 为了在为具有泛型的类构造对象时减少样板,可以使用staticConstructor参数来生成私有构造函数,以及返回新实例的静态方法。 这样,javac将推断变量名称。 因此,通过这样声明:@Data(staticConstructor =“of”)类Foo {private T x;}可以通过写入来创建Foo的新实例:Foo.of(5); 而不必写:new Foo (5);
如果使用了@Data注解
@Data public class DataExample {
private final String name;
@Setter(AccessLevel.PACKAGE) private int age;
private double score;
private String[] tags;
@ToString(includeFieldNames=true)
@Data(staticConstructor="of")
public static class Exercise<T> {
private final String name;
private final T value;
}
}
不加lombok注解的Pojo的写法
public class DataExample {
private final String name;
private int age;
private double score;
private String[] tags;
public DataExample(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
void setAge(int age) {
this.age = age;
}
public int getAge() {
return this.age;
}
public void setScore(double score) {
this.score = score;
}
public double getScore() {
return this.score;
}
public String[] getTags() {
return this.tags;
}
public void setTags(String[] tags) {
this.tags = tags;
}
@Override public String toString() {
return "DataExample(" + this.getName() + ", " + this.getAge() + ", " + this.getScore() + ", " + Arrays.deepToString(this.getTags()) + ")";
}
protected boolean canEqual(Object other) {
return other instanceof DataExample;
}
@Override public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof DataExample)) return false;
DataExample other = (DataExample) o;
if (!other.canEqual((Object)this)) return false;
if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false;
if (this.getAge() != other.getAge()) return false;
if (Double.compare(this.getScore(), other.getScore()) != 0) return false;
if (!Arrays.deepEquals(this.getTags(), other.getTags())) return false;
return true;
}
@Override public int hashCode() {
final int PRIME = 59;
int result = 1;
final long temp1 = Double.doubleToLongBits(this.getScore());
result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode());
result = (result*PRIME) + this.getAge();
result = (result*PRIME) + (int)(temp1 ^ (temp1 >>> 32));
result = (result*PRIME) + Arrays.deepHashCode(this.getTags());
return result;
}
public static class Exercise<T> {
private final String name;
private final T value;
private Exercise(String name, T value) {
this.name = name;
this.value = value;
}
//可以看到这里自动生成了of方法
public static <T> Exercise<T> of(String name, T value) {
return new Exercise<T>(name, value);
}
public String getName() {
return this.name;
}
public T getValue() {
return this.value;
}
@Override public String toString() {
return "Exercise(name=" + this.getName() + ", value=" + this.getValue() + ")";
}
protected boolean canEqual(Object other) {
return other instanceof Exercise;
}
@Override public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Exercise)) return false;
Exercise<?> other = (Exercise<?>) o;
if (!other.canEqual((Object)this)) return false;
if (this.getName() == null ? other.getValue() != null : !this.getName().equals(other.getName())) return false;
if (this.getValue() == null ? other.getValue() != null : !this.getValue().equals(other.getValue())) return false;
return true;
}
@Override public int hashCode() {
final int PRIME = 59;
int result = 1;
result = (result*PRIME) + (this.getName() == null ? 43 : this.getName().hashCode());
result = (result*PRIME) + (this.getValue() == null ? 43 : this.getValue().hashCode());
return result;
}
}
}
扩展@ToString
任何类定义都可以用@ToString注释,让lombok生成toString()方法的实现。默认情况下,它会按顺序打印类名以及每个字段,并以逗号分隔。
通过将includeFieldNames参数设置为true,您可以为toString()方法的输出更详细(但也有一些长度)。这是默认的
默认情况下,将打印所有非静态字段。如果要跳过某些字段,可以使用@ ToString.Exclude注释这些字段。或者,您可以使用@ToString(onlyExplicitlyIncluded = true)准确指定要使用的字段,然后使用@ ToString.Include标记要包含的每个字段。
通过将callSuper设置为true,可以将toString的超类实现的输出包含到输出中。但是java.lang.Object中toString()的默认实现几乎毫无意义,因此除非扩展另一个类,否则不要这样做。
还可以在toString中包含方法调用的输出。只能包含不带参数的实例(非静态)方法。为此,请使用@ToString.Include标记方法。
可以使用@ToString.Include(name =“some other name”)更改用于标识成员的名称,并且可以通过@ToString.Include(rank = -1)更改成员的打印顺序。没有等级的成员被认为具有等级0,更高等级的成员被首先打印,并且相同等级的成员以它们在源文件中出现的相同顺序被打印。
ToString小例子:
加注解:
@ToString
public class ToStringExample {
private static final int STATIC_VAR = 10;
private String name;
private Shape shape = new Square(5, 10);
private String[] tags;
@ToString.Exclude private int id;
public String getName() {
return this.name;
}
@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;
}
}
}
等效于:
public class ToStringExample {
private static final int STATIC_VAR = 10;
private String name;
private Shape shape = new Square(5, 10);
private String[] tags;
private int id;
public String getName() {
return this.getName();
}
public static class Square extends Shape {
private final int width, height;
public Square(int width, int height) {
this.width = width;
this.height = height;
}
@Override public String toString() {
return "Square(super=" + super.toString() + ", width=" + this.width + ", height=" + this.height + ")";
}
}
@Override public String toString() {
return "ToStringExample(" + this.getName() + ", " + this.shape + ", " + Arrays.deepToString(this.tags) + ")";
}
}
构造器注解扩展
@NoArgsConstructor
此注释主要与@Data或生成注释的其他构造函数组合使用。
@NoArgsConstructor将生成一个没有参数的构造函数。如果这是不可能的(因为最终字段),将导致编译器错误,除非使用@NoArgsConstructor(force = true),然后使用0 / false / null初始化所有final字段。对于具有约束的字段,例如@NonNull字段,不会生成任何检查,因此请注意,在稍后正确初始化这些字段之前,通常不会满足这些约束。某些java构造(例如hibernate和Service Provider Interface)需要no-args构造函数。
@RequiredArgsConstructor
@RequiredArgsConstructor为每个需要特殊处理的字段生成一个带有1个参数的构造函数。所有未初始化的final字段都会获得一个参数,以及标记为@NonNull的任何字段,这些字段在声明它们时未初始化。对于标有@NonNull的字段,还会生成显式空检查。如果用于标记为@NonNull的字段的任何参数包含null,则构造函数将抛出NullPointerException。参数的顺序与字段在类中的显示顺序相匹配。
@AllArgsConstructor
@AllArgsConstructor为类中的每个字段生成一个带有1个参数的构造函数。标有@NonNull的字段会导致对这些参数进行空检查。
这些注释中的每一个都允许使用替代形式,其中生成的构造函数始终是私有的,并且生成包围私有构造函数的附加静态工厂方法。通过为注释提供staticName值来启用此模式,如下所示:@RequiredArgsConstructor(staticName =“of”)。与普通构造函数不同,这种静态工厂方法将推断泛型。这意味着您的API用户可以编写MapEntry.of(“foo”,5)而不是更长的新MapEntry <String,Integer>(“foo”,5)。
与大多数其他lombok注释不同,显式构造函数的存在不会阻止这些注解生成自己的构造函数。这意味着可以编写自己的专用构造函数,并让lombok生成样板文件。
注意:如果出现冲突(自定义的一个构造函数最终使用与lombok生成的构造函数相同),则会发生编译器错误。
@Log及其他日志注解
就是简化了生成log的代码,直接看例子
@Log
public class LogExample {
public static void main(String... args) {
log.severe("Something's wrong here");
}
}
@Slf4j
public class LogExampleOther {
public static void main(String... args) {
log.error("Something else is wrong here");
}
}
@CommonsLog(topic="CounterLog")
public class LogExampleCategory {
public static void main(String... args) {
log.error("Calling the 'CounterLog' with a message");
}
}
等效于:
public class LogExample {
private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName());
public static void main(String... args) {
log.severe("Something's wrong here");
}
}
public class LogExampleOther {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExampleOther.class);
public static void main(String... args) {
log.error("Something else is wrong here");
}
}
public class LogExampleCategory {
private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog("CounterLog");
public static void main(String... args) {
log.error("Calling the 'CounterLog' with a message");
}
}
资料链接
想要更详细的了解Lombok,推荐查看它的github来阅读更多的使用特性
Lombok快速上手(安装、使用与注解参数)的更多相关文章
- Jenkins快速上手安装
目录 环境准备 - JDK 安装 1. APT 安装 2. WAR包方式运行 3.Docker 方式运行 Jenkins 是一个独立的开源自动化服务器,可以用来自动化与构建.测试.交付或部署软件相关的 ...
- playwright--自动化(一):快速上手
Playwright为现代 Web 应用程序提供可靠的端到端测试. 在JavaScript 和 TypeScript.Python..NET和Java 中都可以使用 Playwright 本人选择py ...
- IDEA中的lombok插件安装以及各注解的详细介绍
IDEA中的lombok插件安装以及各注解的详细介绍 其实对于我们来说, 写好实体类后,直接用快捷方式生成get,set方法,还有 构造方法就行了,但是对于字段比较多的, 如果修改一个属性的话,就要再 ...
- 【图文详解】scrapy安装与真的快速上手——爬取豆瓣9分榜单
写在开头 现在scrapy的安装教程都明显过时了,随便一搜都是要你安装一大堆的依赖,什么装python(如果别人连python都没装,为什么要学scrapy….)wisted, zope interf ...
- 快速上手Ubuntu之安装篇——安装win7,Ubuntu16.04双系统【转】
本文转载自:http://blog.csdn.net/qq_28205153/article/details/52203512 Linux可以说是开发者的系统,对于开发者来说,Linux发行版不仅为我 ...
- Elastic Search快速上手(1):简介及安装配置
前言 最近开始尝试学习Elastic Search,因此决定做一些简单的整理,以供后续参考,快速上手使用ES. 简介 ElasticSearch是一个基于Lucene的搜索服务器.它提供了一个分布式多 ...
- 【学习总结】快速上手Linux玩转典型应用-第7章-WebServer安装和配置讲解
课程目录链接 快速上手Linux玩转典型应用-目录 目录 1. Apache的安装 2. Apache的虚拟主机配置及伪静态操作 3. Nginx的基本操作 4. Nginx伪静态的实现 5. 实例演 ...
- 【学习总结】快速上手Linux玩转典型应用-第3章-CentOS的安装
课程目录链接 快速上手Linux玩转典型应用-目录 目录 1. 虚拟机是什么 2. 在虚拟机中安装CentOS 3. 云服务器介绍 ================================== ...
- 01_MySQL从下载—>安装—>到快速上手
一.MySQL下载 二.MySQL安装 三.MySQL几条简单命令快速上手(增删改查) 一.MySQL下载与安装 下载地址:https://dev.mysql.com/downloads/mysql/ ...
随机推荐
- ffplay源码分析6-音频重采样
本文为作者原创,转载请注明出处:https://www.cnblogs.com/leisure_chn/p/10312713.html ffplay是FFmpeg工程自带的简单播放器,使用FFmpeg ...
- 微信公众号DOM的一个坑
最近不知道写什么,node的源码有点不知道怎么入手,还在努力学习C++中…… 在写微信公众号的时候遇到了一个小bug,有一个tab栏,在开发者工具.IOS手机上都OK,但是一到我的小米note上就GG ...
- PetaPoco源代码学习--1.使用的Attribute介绍
新版本的PetaPoco使用特性进行注解的形式来代替的老版本的映射类的形式.新版本中使用的特性主要包括以下几种: 名称 用途 TableNameAttribute Class 指定POCO实体类对 ...
- 37.Linux驱动调试-根据oops的栈信息,确定函数调用过程
上章链接入口: http://www.cnblogs.com/lifexy/p/8006748.html 在上章里,我们分析了oops的PC值在哪个函数出错的 本章便通过栈信息来分析函数调用过程 1. ...
- Java多线程--锁的优化
Java多线程--锁的优化 提高锁的性能 减少锁的持有时间 一个线程如果持有锁太长时间,其他线程就必须等待相应的时间,如果有多个线程都在等待该资源,整体性能必然下降.所有有必要减少单个线程持有锁的时间 ...
- 【Linux】rpm常用命令及rpm参数介绍
RPM是RedhatPackageManager的缩写,是由RedHat公司开发的软件包安装和管理程序,同Windows平台上的Uninstaller比较类似.使用RPM,用户可以自行安装和管理Lin ...
- 非常可乐(杭电hdu1495)bfs
非常可乐 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Sub ...
- 【C#数据结构系列】排序
一:排序 排序(Sort)是计算机程序设计中的一种重要操作,也是日常生活中经常遇到的问题.例如,字典中的单词是以字母的顺序排列,否则,使用起来非常困难.同样,存储在计算机中的数据的次序,对于处理这些数 ...
- Redis-五种数据类型解析
redis 五种数据结构详解(string,list,set,zset,hash) Redis不仅仅支持简单的key-value类型的数据,同时还提供list,set,zset,hash等数据结构的存 ...
- Apache poi 使用经验分享
我在使用apache poi导入导出Excel做项目过程中,遇到了许许多多的问题,在此简单罗列. 1.xls和xlsx的区分:poi将2003以前和2007以后的excel封装成了两个不同的实现:HS ...