Lombok基本使用
一、Lombok是什么
Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.
翻译:Lombok是一种Java 使用工具,可用来帮助开发人员消除 Java中的冗长代码,尤其是对于简单的Java对象(POJO),它通过注解实现这一目的
使用Lombok前:
/**
* #Description : 用户类
* #Date: 2020/11/11 00:11
* @author : tiankun
*/
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
public User() {
}
public User(Integer id, String username, Date birthday, String sex, String address) {
this.id = id;
this.username = username;
this.birthday = birthday;
this.sex = sex;
this.address = address;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", birthday=" + birthday +
", sex='" + sex + '\'' +
", address='" + address + '\'' +
'}';
}
}
使用Lombok后
/**
* #Description : 用户类
* #Date: 2020/11/11 00:11
* @author : tiankun
*/
@Data
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
}
二、Lombok原理
JSR269规范:插件化注解处理API(Pluggable Annotation Processing API)
JDK6 提供的特性,在 Javac 编译期利用注解做一些事情
@Data 源码
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.SOURCE) // 源代码级别
public @interface Data {
String staticConstructor() default "";
}
@Data 注解,在我们编译后,它会把Get,Set等方法添加到我们的class文件中
用@Data注解,User编译后的Class文件
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//
package com.tk.domain;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable {
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
public User() {
}
public Integer getId() {
return this.id;
}
public String getUsername() {
return this.username;
}
public Date getBirthday() {
return this.birthday;
}
public String getSex() {
return this.sex;
}
public String getAddress() {
return this.address;
}
public void setId(Integer id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public void setSex(String sex) {
this.sex = sex;
}
public void setAddress(String address) {
this.address = address;
}
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof User)) {
return false;
} else {
User other = (User)o;
if (!other.canEqual(this)) {
return false;
} else {
label71: {
Object this$id = this.getId();
Object other$id = other.getId();
if (this$id == null) {
if (other$id == null) {
break label71;
}
} else if (this$id.equals(other$id)) {
break label71;
}
return false;
}
Object this$username = this.getUsername();
Object other$username = other.getUsername();
if (this$username == null) {
if (other$username != null) {
return false;
}
} else if (!this$username.equals(other$username)) {
return false;
}
label57: {
Object this$birthday = this.getBirthday();
Object other$birthday = other.getBirthday();
if (this$birthday == null) {
if (other$birthday == null) {
break label57;
}
} else if (this$birthday.equals(other$birthday)) {
break label57;
}
return false;
}
Object this$sex = this.getSex();
Object other$sex = other.getSex();
if (this$sex == null) {
if (other$sex != null) {
return false;
}
} else if (!this$sex.equals(other$sex)) {
return false;
}
Object this$address = this.getAddress();
Object other$address = other.getAddress();
if (this$address == null) {
if (other$address == null) {
return true;
}
} else if (this$address.equals(other$address)) {
return true;
}
return false;
}
}
}
protected boolean canEqual(Object other) {
return other instanceof User;
}
public int hashCode() {
int PRIME = true;
int result = 1;
Object $id = this.getId();
int result = result * 59 + ($id == null ? 43 : $id.hashCode());
Object $username = this.getUsername();
result = result * 59 + ($username == null ? 43 : $username.hashCode());
Object $birthday = this.getBirthday();
result = result * 59 + ($birthday == null ? 43 : $birthday.hashCode());
Object $sex = this.getSex();
result = result * 59 + ($sex == null ? 43 : $sex.hashCode());
Object $address = this.getAddress();
result = result * 59 + ($address == null ? 43 : $address.hashCode());
return result;
}
public String toString() {
return "User(id=" + this.getId() + ", username=" + this.getUsername() + ", birthday=" + this.getBirthday() + ", sex=" + this.getSex() + ", address=" + this.getAddress() + ")";
}
}
三、安装
1、导入jar包 / 资源
安装lombok插件的前提就是需要下载lombok,jar。
当然也如果是Maven项目直接可以在maven中导入,版本随你意,我使用的就是maven
<!-- lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.12</version>
</dependency>
2、安装lombok插件
2.1 Eclipse
在下载完lombok.jar。右键点击。打开方式选择——》java(TM) Platform SE binary
’插件安装成功,然后把你的lombok.jar导入到你项目中去(如果没有安装插件,则使用lombok,jar包中的注解不起作用)
2.2 IDEA
直接在 Setting-> Plugins 里面搜索 lombok下载 重启即可
四、Lombok的常用注解
1、Getter、Setter
①、字段上:对该字段进行操作
②、类上:对类中所有的字段进行操作
public class User implements Serializable {
@Setter()
@Getter(AccessLevel.PRIVATE) //指定修饰符 默认是 AccessLevel.PUBLIC
private Integer id;
private String username;
private Date birthday;
private String sex;
private String address;
}
特殊情况:
1、如果字段是被 static修饰的,则不会生成该字段的 Getter、Setter方法
2、如果字段是被finnal 修饰的,则只会生成 Get方法 不会生成 Set 方法
如果我们不想某个字段被生成Getter,Setter方法,可以使用参数: AccessLevel.NONE 来设置
2、ToString
static修饰的变量 不会被打印输出, final修饰的的变量可以被打印输出
- of 只打印 {} 中的字段
- exclude 打印除了 { } 中的所有字段
@Getter
@Setter
@ToString(of = {"id"})
//@ToString(exclude = {"name"})
public class User implements Serializable {
static String s = "";
final String ss = "";
private Integer id;
private String name;
public static void main(String[] args) {
User user = new User();
user.setId(18);
user.setName("田坤");
System.out.println(user);
}
}
User(id=18)
3、EqualsAndHashCode
帮我们生成 hashCodo 和 equals 方法
- of 只操作 {} 中的字段
- exclude 操作除了 { } 中的所有字段
lombok帮我们生成的 equals 和 hashCode方法
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (!(o instanceof User)) {
return false;
} else {
User other = (User)o;
if (!other.canEqual(this)) {
return false;
} else {
label47: {
Object this$ss = this.getSs();
Object other$ss = other.getSs();
if (this$ss == null) {
if (other$ss == null) {
break label47;
}
} else if (this$ss.equals(other$ss)) {
break label47;
}
return false;
}
Object this$id = this.getId();
Object other$id = other.getId();
if (this$id == null) {
if (other$id != null) {
return false;
}
} else if (!this$id.equals(other$id)) {
return false;
}
Object this$name = this.getName();
Object other$name = other.getName();
if (this$name == null) {
if (other$name != null) {
return false;
}
} else if (!this$name.equals(other$name)) {
return false;
}
return true;
}
}
}
protected boolean canEqual(Object other) {
return other instanceof User;
}
public int hashCode() {
int PRIME = true;
int result = 1;
Object $ss = this.getSs();
int result = result * 59 + ($ss == null ? 43 : $ss.hashCode());
Object $id = this.getId();
result = result * 59 + ($id == null ? 43 : $id.hashCode());
Object $name = this.getName();
result = result * 59 + ($name == null ? 43 : $name.hashCode());
return result;
}
4、NonNull
NonNull 表示修饰的变量不能为空,如果为空则会抛出一个异常
@NonNull
private String name;
public void test(@NonNull String str){
}
编译后 lombok 在class文件中帮我们做的事:
public void setName(@NonNull String name) {
if (name == null) {
throw new NullPointerException("name is marked non-null but is null");
} else {
this.name = name;
}
}
public void test(@NonNull String str) {
if (str == null) {
throw new NullPointerException("str is marked non-null but is null");
}
}
5、Constructor
- @NoArgsConstructor 生成无参的构造函数
- @RequiredArgsConstructor 生成部分参数的构造函数
- 只识别 @NonNull 修饰的字段 和 没有初始值的 final 修饰的字段
- @AllArgsConstructor 生成全参的构造函数
@RequiredArgsConstructor
public class User implements Serializable {
static String s = "";
final String ss;
private Integer id;
@NonNull private String name;
}
编译后的class文件
public User(String ss, @NonNull String name) {
if (name == null) {
throw new NullPointerException("name is marked non-null but is null");
} else {
this.ss = ss;
this.name = name;
}
}
6、Data
集四个职责于一身
- Getter、Setter
- ToString
- EqualsAndHashCode
- RequiredArgsConstructor
7、Builder
可以使用 链式编程 来传入参数和调用方法
@Builder
@ToString
public class User implements Serializable {
static String s = "";
final String ss;
private Integer id;
private String name;
}
class Test{
public static void main(String[] args) {
User user = User.builder().id(11).name("田坤").build();
System.out.println(user);
}
}
8、Log 启用日志
https://www.jianshu.com/p/42b1bcb994a8
9、Val (@Value)
一个未定义的类型
val map = new HashMap<String,String>();
10、Clearup
自动关闭一些资源
public void demo(){
//创建源
System.out.println();
File srcFile = new File("D:/WorkSpace/IdeaWorksSpace/javabase/IO/src/part2/ave1.jpg");
File destFile = new File("D:/WorkSpace/IdeaWorksSpace/javabase/IO/src/part2/ave1Copy.jpg");
//选择流
@Cleanup InputStream is = null;
@Cleanup OutputStream os = null;
//操作
try {
is = new FileInputStream(srcFile);
os = new FileOutputStream(destFile);
//缓存容器
byte[] flush = new byte[1024];
int len = -1;
while ((len = is.read(flush))!= -1){
os.write(flush,0,len);
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Cleanup 最后会帮我们关闭 InputStream 和 OutputStream ,他也是在编译后在 finally里面 关闭资源;
本文地址:https://blog.csdn.net/qq_41965731/article/details/109614145
上一篇: ArrayList 一篇就够