一:在開發工具中安裝插件:
Eclipse:
下載下傳位址:lombok
将下載下傳的lombok.jar檔案,放到eclipse安裝路徑,該jar包也就是lombok插件的jar檔案了
打開eclipse.ini檔案,添加如下内容:
-javaagent:lombok.jar
-Xbootclasspath/a:lombok.jar
重新開機eclipse
IDEA:
可以線上安裝lombok的插件
settings -> plugins -> 在搜尋框輸入lombok -> 安裝
二:在pom.xml中,引入依賴
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
三:Lombok用法
注解說明
-
:用在局部變量前面,相當于将變量聲明為finalval
public static void main(String[] args) {
val sets = new HashSet<String>();
val lists = new ArrayList<String>();
val maps = new HashMap<String, String>();
//=>相當于如下
final Set<String> sets2 = new HashSet<>();
final List<String> lists2 = new ArrayList<>();
final Map<String, String> maps2 = new HashMap<>();
}
-
:給方法參數增加這個注解會自動在方法内對該參數進行是否為空的校驗,如果為空,則抛出NPE(NullPointerException)@NonNull
public void notNullExample(@NonNull String string) {
string.length();
}
//=>相當于
public void notNullExample(String string) {
if (string != null) {
string.length();
} else {
throw new NullPointerException("null");
}
}
-
:自動管理資源,用在局部變量之前,在目前變量範圍内即将執行完畢退出之前會自動清理資源,自動生成try-finally這樣的代碼來關閉流@Cleanup
public static void main(String[] args) {
try {
@Cleanup InputStream inputStream = new FileInputStream(args[0]);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//=>相當于
InputStream inputStream = null;
try {
inputStream = new FileInputStream(args[0]);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
-
:用在屬性上,再也不用自己手寫setter和getter方法了,還可以指定通路範圍@Getter/@Setter
@Setter(AccessLevel.PUBLIC)
@Getter(AccessLevel.PROTECTED)
private int id;
private String shap;
-
:用在類上,可以自動覆寫toString方法,當然還可以加其他參數,@ToString
例如@ToString(exclude=”id”)排除id屬性,或者@ToString(callSuper=true, includeFieldNames=true)調用父類的toString方法,包含所有屬性
@ToString(exclude = "id", callSuper = true, includeFieldNames = true)
public class LombokDemo {
private int id;
private String name;
private int age;
public static void main(String[] args) {
//輸出LombokDemo([email protected], name=null, age=0)
System.out.println(new LombokDemo());
}
}
-
:用在類上,自動生成equals方法和hashCode方法@EqualsAndHashCode
@EqualsAndHashCode(exclude = {"id", "shape"}, callSuper = false)
public class LombokDemo {
private int id;
private String shap;
}
-
:用在類上,自動生成無參構造和使用所有參數的構造函數以及把所有@NonNull屬性作為參數的構造函數,如果指定staticName = “of”參數,同時還會生成一個傳回類對象的靜态工廠方法,比使用構造函數友善很多@NoArgsConstructor, @RequiredArgsConstructor , @AllArgsConstructor
@NoArgsConstructor
@RequiredArgsConstructor(staticName = "of")
@AllArgsConstructor
public class LombokDemo {
@NonNull
private int id;
@NonNull
private String shap;
private int age;
public static void main(String[] args) {
new LombokDemo(1, "circle");
//使用靜态工廠方法
LombokDemo.of(2, "circle");
//無參構造
new LombokDemo();
//包含所有參數
new LombokDemo(1, "circle", 2);
}
}
-
:注解在類上,相當于同時使用了@ToString、@EqualsAndHashCode、@Getter、@Setter和@RequiredArgsConstrutor這些注解,對于POJO類十分有用@Data
在IntelliJ中按下Ctrl+F12就可以看到Lombok已經為我們自動生成了一系列的方法。
import lombok.Data;
@Data
public class Menu {
private String shopId;
private String skuMenuId;
private String skuName;
private String normalizeSkuName;
private String dishMenuId;
private String dishName;
private String dishNum;
//預設門檻值
private float thresHold = 0;
//新門檻值
private float newThresHold = 0;
//總得分
private float totalScore = 0;
}
-
:用在類上,是@Data的不可變形式,相當于為屬性添加final聲明,隻提供getter方法,而不提供setter方法@Value
@Value
public class LombokDemo {
@NonNull
private int id;
@NonNull
private String shap;
private int age;
//相當于
private final int id;
public int getId() {
return this.id;
}
...
}
-
:用在類、構造器、方法上,為你提供複雜的builder APIs,讓你可以像如下方式一樣調用Person.builder().name(“Adam Savage”).city(“San Francisco”).job(“Mythbusters”).job(“Unchained Reaction”).build();更多說明參考Builder@Builder
@Builder
public class BuilderExample {
private String name;
private int age;
@Singular
private Set<String> occupations;
public static void main(String[] args) {
BuilderExample test = BuilderExample.builder().age(11).name("test").build();
}
}
-
:自動抛受檢異常,而無需顯式在方法上使用throws語句@SneakyThrows
import lombok.SneakyThrows;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
public class Test {
@SneakyThrows()
public void read() {
InputStream inputStream = new FileInputStream("");
}
@SneakyThrows
public void write() {
throw new UnsupportedEncodingException();
}
//相當于
public void read() throws FileNotFoundException {
InputStream inputStream = new FileInputStream("");
}
public void write() throws UnsupportedEncodingException {
throw new UnsupportedEncodingException();
}
}
-
:用在方法上,将方法聲明為同步的,并自動加鎖,而鎖對象是一個私有的屬性 l o c k 或 lock或 lock或LOCK,而java中的synchronized關鍵字鎖對象是this,鎖在this或者自己的類對象上存在副作用,就是你不能阻止非受控代碼去鎖this或者類對象,這可能會導緻競争條件或者其它線程錯誤@Synchronized
public class SynchronizedDemo {
@Synchronized
public static void hello() {
System.out.println("world");
}
//相當于
private static final Object $LOCK = new Object[0];
public static void hello() {
synchronized ($LOCK) {
System.out.println("world");
}
}
}
-
:可以替代經典的Double Check Lock樣闆代碼@Getter(lazy=true)
public class GetterLazyExample {
@Getter(lazy = true)
private final double[] cached = expensive();
private double[] expensive() {
double[] result = new double[1000000];
for (int i = 0; i < result.length; i++) {
result[i] = Math.asin(i);
}
return result;
}
}
import java.util.concurrent.atomic.AtomicReference;
public class GetterLazyExample {
private final AtomicReference<java.lang.Object> cached = new AtomicReference<>();
public double[] getCached() {
java.lang.Object value = this.cached.get();
if (value == null) {
synchronized (this.cached) {
value = this.cached.get();
if (value == null) {
final double[] actualValue = expensive();
value = actualValue == null ? this.cached : actualValue;
this.cached.set(value);
}
}
}
return (double[]) (value == this.cached ? null : value);
}
private double[] expensive() {
double[] result = new double[1000000];
for (int i = 0; i < result.length; i++) {
result[i] = Math.asin(i);
}
return result;
}
}
-
:根據不同的注解生成不同類型的log對象,但是執行個體名稱都是log,有六種可選實作類@Log
-
Creates log = org.apache.commons.logging.LogFactory.getLog(LogExample.class);@CommonsLog
-
Creates log = java.util.logging.Logger.getLogger(LogExample.class.getName());@Log
-
Creates log = org.apache.log4j.Logger.getLogger(LogExample.class);@Log4j
-
Creates log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class);@Log4j2
-
Creates log = org.slf4j.LoggerFactory.getLogger(LogExample.class);@Slf4j
-
Creates log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);@XSlf4j
-
// SpringBoot 下
@Log
public class LombokDemo{
log.info("加上注解後,可直接使用。需要列印的消息!");
}
//相當于
public class LombokDemo{
// 1. create log 2. get log config file 3.start log
public static Log log = LogFactory.getLog(TestLog.class);
log.info("沒加注解需要手動建立。需要列印的消息!");
}