lombok 簡化 Java 代碼
1.介紹
Lombok 是一種 Java 實用工具世蔗,可用來幫助開發(fā)人員消除 Java 的冗長,尤其是對于簡單的 Java 對象(POJO)惹想。它通過注解實現(xiàn)這一目的。Lombok官網(wǎng):https://projectlombok.org
2.idea使用
1.引入依賴
在項目中添加Lombok依賴jar,在pom文件中添加如下部分裤翩。(不清楚版本可以在Maven倉庫中搜索)
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
<scope>provided</scope>
</dependency>
2.idea插件
3.注解的說明
@NonNull
or: How I learned to stop worrying and love the NullPointerException.
該注解使用在屬性上拳亿,該注解用于屬的非空檢查晴股,當放在setter方法的字段上,將生成一個空檢查肺魁,如果為空电湘,則拋出NullPointerException。
該注解會默認是生成一個無參構(gòu)造鹅经。
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Integer uid;
@NonNull
@Setter
@Getter
private String username;
private boolean flag;
}
如果測試的時候username為空的情況下結(jié)果如下:
Exception in thread "main" java.lang.NullPointerException: username
at com.taojian.tblog.lombok.User.setUsername(User.java:28)
at com.taojian.tblog.lombok.Test.main(Test.java:15)
@Cleanup
Automatic resource management: Call your close() methods safely with no hassle.
該注解使用在屬性前胡桨,該注解是用來保證分配的資源被釋放。在本地變量上使用該注解瞬雹,任何后續(xù)代碼都將封裝在try/finally中昧谊,確保當前作用于中的資源被釋放。默認@Cleanup清理的方法為close酗捌,可以使用value指定不同的方法名稱
import java.io.*;
public class CleanupExample {
public static void main(String[] args) throws IOException {
InputStream in = new FileInputStream(args[0]);
try {
OutputStream out = new FileOutputStream(args[1]);
try {
byte[] b = new byte[10000];
while (true) {
int r = in.read(b);
if (r == -1) break;
out.write(b, 0, r);
}
} finally {
if (out != null) {
out.close();
}
}
} finally {
if (in != null) {
in.close();
}
}
}
}
使用后:
import lombok.Cleanup;
import java.io.*;
public class CleanupExample {
public static void main(String[] args) throws IOException {
@Cleanup InputStream in = new FileInputStream(args[0]);
@Cleanup OutputStream out = new FileOutputStream(args[1]);
byte[] b = new byte[10000];
while (true) {
int r = in.read(b);
if (r == -1) break;
out.write(b, 0, r);
}
}
}
@Getter/@Setter
Never write public int getFoo() {return foo;} again.
@Getter 就相對于是屬性的get()方法呢诬,@Setter就相當于屬性的set()方法。
The generated getter/setter method will be public unless you explicitly specify an AccessLevel, as shown in the example below. Legal access levels are PUBLIC, PROTECTED, PACKAGE, and PRIVATE.
這句話的意思就是可以指定設(shè)置的getter,setter的方法的權(quán)限筹裕, @Setter(AccessLevel.PROTECTED) 這個就表示是一個protected屬性歧强。
@Setter(AccessLevel.PROTECTED) private String name;
/**
* Changes the name of this person.
*
* @param name The new value.
*/
protected void setName(String name) {
this.name = name;
}
使用前:
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Integer uid;
private String username;
private String password;
public Integer getUid() {
return uid;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
}
使用后:
@Getter
@Setter
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Integer uid;
private String username;
private String password;
}
@ToString
No need to start a debugger to see your fields: Just let lombok generate a toString for you!
1、如果需要可以通過注釋參數(shù)includeFieldNames來控制輸出中是否包含的屬性名稱狗唉。
2、可以通過exclude參數(shù)中包含字段名稱涡真,可以從生成的方法中排除特定字段分俯。
3肾筐、可以通過callSuper參數(shù)控制父類的輸出。
@ToString(exclude="column")
意義:排除column列所對應(yīng)的元素缸剪,即在生成toString方法時不包含column參數(shù)吗铐;
@ToString(exclude={"column1","column2"})
意義:排除多個column列所對應(yīng)的元素,其中間用英文狀態(tài)下的逗號進行分割杏节,即在生成toString方法時不包含多個column參數(shù)唬渗;
@ToString(of="column")
意義:只生成包含column列所對應(yīng)的元素的參數(shù)的toString方法,即在生成toString方法時只包含column參數(shù)奋渔;镊逝;
@ToString(of={"column1","column2"})
意義:只生成包含多個column列所對應(yīng)的元素的參數(shù)的toString方法,其中間用英文狀態(tài)下的逗號進行分割嫉鲸,即在生成toString方法時只包含多個column參數(shù)蹋半;
使用前:
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Integer uid;
private String username;
private String password;
@Override
public String toString() {
return super.toString();
}
}
使用后:
@ToString
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Integer uid;
private String username;
private String password;
@EqualsAndHashCode
Equality made easy: Generates hashCode and equals implementations from the fields of your object..
可以使用@EqualsAndHashCodelombok生成equals(Object other)和hashCode()方法的實現(xiàn)來注釋任何類定義
作用于類,自動重寫類的equals()充坑、hashCode()方法减江。常用的參數(shù)有exclude(指定方法中不包含的屬性)、callSuper(方法中是否包含父類ToString()方法返回的值)
使用前:
使用后:
import lombok.EqualsAndHashCode;
@EqualsAndHashCode
public class EqualsAndHashCodeExample {
private transient int transientVar = 10;
private String name;
private double score;
@EqualsAndHashCode.Exclude private Shape shape = new Square(5, 10);
private String[] tags;
@EqualsAndHashCode.Exclude private int id;
public String getName() {
return this.name;
}
// 因為有繼承的關(guān)系捻爷,所以要設(shè)置true辈灼,如果沒有,只繼承了Object類的時候也榄,就會報錯
@EqualsAndHashCode(callSuper=true)
public static class Square extends Shape {
private final int width, height;
public Square(int width, int height) {
this.width = width;
this.height = height;
}
}
}
使用后:
import java.util.Arrays;
public class EqualsAndHashCodeExample {
private transient int transientVar = 10;
private String name;
private double score;
private Shape shape = new Square(5, 10);
private String[] tags;
private int id;
public String getName() {
return this.name;
}
@Override public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof EqualsAndHashCodeExample)) return false;
EqualsAndHashCodeExample other = (EqualsAndHashCodeExample) o;
if (!other.canEqual((Object)this)) return false;
if (this.getName() == null ? other.getName() != null : !this.getName().equals(other.getName())) return false;
if (Double.compare(this.score, other.score) != 0) return false;
if (!Arrays.deepEquals(this.tags, other.tags)) return false;
return true;
}
@Override public int hashCode() {
final int PRIME = 59;
int result = 1;
final long temp1 = Double.doubleToLongBits(this.score);
result = (result*PRIME) + (this.name == null ? 43 : this.name.hashCode());
result = (result*PRIME) + (int)(temp1 ^ (temp1 >>> 32));
result = (result*PRIME) + Arrays.deepHashCode(this.tags);
return result;
}
protected boolean canEqual(Object other) {
return other instanceof EqualsAndHashCodeExample;
}
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 boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof Square)) return false;
Square other = (Square) o;
if (!other.canEqual((Object)this)) return false;
if (!super.equals(o)) return false;
if (this.width != other.width) return false;
if (this.height != other.height) return false;
return true;
}
@Override public int hashCode() {
final int PRIME = 59;
int result = 1;
result = (result*PRIME) + super.hashCode();
result = (result*PRIME) + this.width;
result = (result*PRIME) + this.height;
return result;
}
protected boolean canEqual(Object other) {
return other instanceof Square;
}
}
}
@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor
Constructors made to order: Generates constructors that take no arguments, one argument per final / non-nullfield, or one argument for every field.
@NoArgsConstructor 相對于:
public User(){}
@RequiredArgsConstructor 該注解使用在類上巡莹,使用類中所有帶有 @NonNull 注解的或者帶有 final 修飾的成員變量生成對應(yīng)的構(gòu)造方法。
@NoArgsConstructor 相對于:
public User(Integer uid, String username, boolean flag) {
this.uid = uid;
this.username = username;
this.flag = flag;
}
@Data
All together now: A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, and @Setter on all non-final fields, and @RequiredArgsConstructor!
該注解使用在類上甜紫,該注解是最常用的注解降宅,它結(jié)合了@ToString,@EqualsAndHashCode囚霸, @Getter和@Setter腰根。本質(zhì)上使用@Data注解,類默認@ToString和@EqualsAndHashCode以及每個字段都有@Setter和@getter拓型。該注解也會生成一個公共構(gòu)造函數(shù)额嘿,可以將任何@NonNull和final字段作為參數(shù)。
雖然@Data注解非常有用劣挫,但是它沒有與其他注解相同的控制粒度册养。@Data提供了一個可以生成靜態(tài)工廠的單一參數(shù),將staticConstructor參數(shù)設(shè)置為所需要的名稱压固,Lombok自動生成的構(gòu)造函數(shù)設(shè)置為私有球拦,并提供公開的給定名稱的靜態(tài)工廠方法。
/**
* @description:
* @author: taojian
* @create: 2018-09-30 22:32
* 實際上含有這些方法
* getUid
* getUsername
* isFlag 這里是isFlag(),而不是getFlag()
* setUid
* setUsername
* setFlag
* equals
* hashCode
* canEqual
* toString
**/
@Data
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Integer uid;
private String username;
private boolean flag;
@Data
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Integer uid;
private String username;
private boolean flag;
}
@Value
Immutable classes made very easy.
這個注解用在 類 上坎炼,會生成含所有參數(shù)的構(gòu)造方法愧膀,get 方法,此外還提供了equals点弯、hashCode扇调、toString 方法矿咕。 注意:沒有setter 類似@Data
/**
* @description:
* @author: taojian
* @create: 2018-09-30 22:32
* User
* getUid
* getUsername
* isFlag
* equals
* hashCode
* toString
* serialVersionUID
* uid
* username
* flag
**/
@Value
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Integer uid;
private String username;
private boolean flag;
}
@Builder
... and Bob's your uncle: No-hassle fancy-pants APIs for object creation!
Project Lombok的@Builder 是一種在不編寫樣板代碼的情況下使用Builder模式的有用機制抢肛。我們可以將此注釋應(yīng)用于 類 或方法。
在類上使用@Builder
/**
* @description:
* User
* getUid
* getUsername
* isFlag
* builder 這個方法是增加的方法
**/
@Getter
@Builder
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private Integer uid;
private String username;
private boolean flag;
}
public class Test {
public static void main(String[] args) {
User user = User.builder().username("taojian").flag(true).uid(1).build();
System.out.println(user.getUsername().equals("taojian")); // true
}
}
2. 在方法上使用@Builder
假設(shè)我們正在使用我們想要使用構(gòu)建器構(gòu)造的對象碳柱,但我們無法修改源或擴展類捡絮。
首先,讓我們使用Lombok的@Value注釋創(chuàng)建一個快速示例:
@Value
final class ImmutableClient {
private int id;
private String name;
}
現(xiàn)在我們有一個帶有兩個不可變成員的最終 類莲镣,它們的getter和一個all-arguments構(gòu)造函數(shù)福稳。
我們介紹了如何在Class上 使用@Builder,但我們也可以在方法上使用它瑞侮。我們將使用此功能來解決無法修改或擴展ImmutableClient的問題的圆。
接下來,我們將使用創(chuàng)建ImmutableClients的方法創(chuàng)建一個新類:
class ClientBuilder {
@Builder(builderMethodName = "builder")
public static ImmutableClient newClient(int id, String name) {
return new ImmutableClient(id, name);
}
}
這個注解創(chuàng)建了一個名為法生成器()是返回一個生成器來創(chuàng)建ImmutableClients半火。
現(xiàn)在我們可以構(gòu)建一個ImmutableClient:
ImmutableClient testImmutableClient = ClientBuilder.builder()
.name("foo")
.id(1)
.build();
assertThat(testImmutableClient.getName())
.isEqualTo("foo");
assertThat(testImmutableClient.getId())
.isEqualTo(1);
@SneakyThrows
To boldly throw checked exceptions where no one has thrown them before!
該注解使用在方法上越妈,這個注解用在 方法 上,可以將方法中的代碼用 try-catch 語句包裹起來钮糖,捕獲異常并在 catch 中用 Lombok.sneakyThrow(e) 把異常拋出梅掠,可以使用 @SneakyThrows(Exception.class) 的形式指定拋出哪種異常。該注解需要謹慎使用
使用前:
import lombok.Lombok;
public class SneakyThrowsExample implements Runnable {
public String utf8ToString(byte[] bytes) {
try {
return new String(bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw Lombok.sneakyThrow(e);
}
}
public void run() {
try {
throw new Throwable();
} catch (Throwable t) {
throw Lombok.sneakyThrow(t);
}
}
}
使用后:
import lombok.SneakyThrows;
public class SneakyThrowsExample implements Runnable {
@SneakyThrows(UnsupportedEncodingException.class)
public String utf8ToString(byte[] bytes) {
return new String(bytes, "UTF-8");
}
@SneakyThrows
public void run() {
throw new Throwable();
}
}
@Synchronized
synchronized done right: Don't expose your locks.
該注解使用在類或者實例方法上店归,Synchronized在一個方法上阎抒,使用關(guān)鍵字可能會導(dǎo)致結(jié)果和想要的結(jié)果不同,因為多線程情況下會出現(xiàn)異常情況消痛。Synchronized
關(guān)鍵字將在this示例方法情況下鎖定當前對象且叁,或者class講臺方法的對象上多鎖定。這可能會導(dǎo)致死鎖現(xiàn)象秩伞。一般情況下建議鎖定一個專門用于此目的的獨立鎖谴古,而不是允許公共對象進行鎖定。該注解也是為了達到該目的稠歉。
使用前:
public class SynchronizedExample {
private static final Object $LOCK = new Object[0];
private final Object $lock = new Object[0];
private final Object readLock = new Object();
public static void hello() {
synchronized($LOCK) {
System.out.println("world");
}
}
public int answerToLife() {
synchronized($lock) {
return 42;
}
}
public void foo() {
synchronized(readLock) {
System.out.println("bar");
}
}
}
使用后:
mport lombok.Synchronized;
public class SynchronizedExample {
private final Object readLock = new Object();
@Synchronized
public static void hello() {
System.out.println("world");
}
@Synchronized
public int answerToLife() {
return 42;
}
@Synchronized("readLock")
public void foo() {
System.out.println("bar");
}
}
@Log @Slf4j
Captain's Log, stardate 24435.7: "What was that line again?"
日志類型
experimental
Head to the lab: The new stuff we're working on.
@CommonsLog
Creates private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(LogExample.class);
@Flogger
Creates private static final com.google.common.flogger.FluentLogger log = com.google.common.flogger.FluentLogger.forEnclosingClass();
@JBossLog
Creates private static final org.jboss.logging.Logger log = org.jboss.logging.Logger.getLogger(LogExample.class);
@Log
Creates private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(LogExample.class.getName());
@Log4j
Creates private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(LogExample.class);
@Log4j2
Creates private static final org.apache.logging.log4j.Logger log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class);
@Slf4j
Creates private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExample.class);
@XSlf4j
Creates private static final org.slf4j.ext.XLogger log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);
使用前:
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");
}
}
使用后:
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
@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");
}
}
參考文章鏈接:
https://www.baeldung.com/lombok-builder
https://blog.csdn.net/motui/article/details/79012846
https://blog.csdn.net/motui/article/details/79012846
https://segmentfault.com/a/1190000005133786
歡迎大家關(guān)注我的公眾號掰担,會定期給大家更新一些新的文章,和一些新的看法怒炸〈ィ互相交流