lombok 簡化java代碼注解
安裝lombok插件
以intellij ide為例
File-->Setting-->Plugins-->搜索“lombok plugin”,安裝后重啟ide
lombok 注解
lombok 提供的注解不多,可以參考官方視頻的講解和官方文檔。
Lombok 注解在線幫助文檔:https://projectlombok.org/features/index.html
下面介紹幾個我常用的 lombok 注解:
@Data
:注解在類上;提供類所有屬性的getting
和setting
方法,此外還提供了equals
、canEqual
、hashCode
、toString
方法@Setter
:注解在屬性上;為屬性提供setting
方法@Getter
:注解在屬性上;為屬性提供getting
方法@Log4j
:注解在類上;為類提供一個 屬性名為log 的log4j
日志對象@NoArgsConstructor
:注解在類上;為類提供一個無參的構造方法@AllArgsConstructor
:注解在類上;為類提供一個全參的構造方法@NonNull
:注解在參數上,可以省略重復的if( null == persion)
這類異常處理@Cleanup
:注解在輸入輸出流等需要釋放資源的變量上,不需要寫額外繁瑣而重復的釋放資源代碼
不使用lombok
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();
}
}
}
}
使用lombok
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);
}
}
}
val
:最終局部變量,在迭代器循環時刻做簡單縮寫。
不使用lombok
public void example2() {
final HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put(0, "zero");
map.put(5, "five");
for (final Map.Entry<Integer, String> entry : map.entrySet()) {
System.out.printf("%d: %s\n", entry.getKey(), entry.getValue());
}
}
使用lombok
public void example2() {
val map = new HashMap<Integer, String>();
map.put(0, "zero");
map.put(5, "five");
for (val entry : map.entrySet()) {
System.out.printf("%d: %s\n", entry.getKey(), entry.getValue());
}
}
下面是簡單示例
不使用 lombok 的方案
public class Person {
private String id;
private String name;
private String identity;
private Logger log = Logger.getLogger(Person.class);
public Person() {
}
public Person(String id, String name, String identity) {
this.id = id;
this.name = name;
this.identity = identity;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getIdentity() {
return identity;
}
public void setId(String id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setIdentity(String identity) {
this.identity = identity;
}
}
使用 lombok 的方案
@Data
@Log4j
@NoArgsConstructor
@AllArgsConstructor
public class Person {
private String id;
private String name;
private String identity;
}
參考文檔: