一. 為什么要用@Cleanup?
在IO流的學(xué)習(xí)中,每次都要在finally里面關(guān)閉資源,是不是很讓人頭疼?那么有沒有好的方法去生成這樣的重復(fù)代碼。方法有兩種:一種是使用Lombok的@Cleanup,另一種是使用jdk1.7+的try-with-resources語法糖。我個人推薦使用try-with-resources語法糖,因為它是jdk提供的,所以受眾更廣,別人能更容易讀懂你的代碼,也不用綁定插件才能使用。在關(guān)閉流(資源)的時候,經(jīng)常使用到以下代碼
try {
// to do something
}finally {
if (in != null) {
in.close();
}
}
這樣的代碼,如同模板一樣,出現(xiàn)在程序各個地方。下面演示兩種方法是如何自動關(guān)閉流的。
二. @Cleanup如何使用?
public class CleanupExample {
public static void main(String[] args) throws IOException {
try(InputStream inputStream =
new FileInputStream(".\\src\\main\\java\\com\\cauchy6317\\common\\Cleanup\\ForCleanupExample.txt")){
// to do something
}
@Cleanup Reader fileReader =
new FileReader(".\\src\\main\\java\\com\\cauchy6317\\common\\Cleanup\\ForCleanupExample1.txt");
// to do something
}
}
第一種是try-with-resources語法糖,在try后面初始化流,可以同時初始化多個。第二種是@Cleanup注解模式。
在這里插入圖片描述
從反編譯的代碼來看,@Cleanup更簡潔些。它使用了“Collections.singletonList(fileReader).get(0) != null”進(jìn)行資源對象fileReader的判空,我不知道這樣做有什么好處(哪位前輩能解釋一下,十分感謝)。還有,在try-with-catch語法糖中生成的“Object var2 = null;”也不清楚用意何在。
三. @Cleanup源碼
@Target(ElementType.LOCAL_VARIABLE)
@Retention(RetentionPolicy.SOURCE)
public @interface Cleanup {
/** @return The name of the method that cleans up the resource. By default, 'close'. The method must not have any parameters. */
String value() default "close";
}
注解屬性:value,也是我覺得Lombok比較好的一點,它可以指定關(guān)閉方法的方法名。
四. 特別說明
本文已經(jīng)收錄在Lombok注解系列文章總覽中,并繼承上文中所提的特別說明。
源碼地址:gitee