注解類型 Cleanup


@Target(LOCAL_VARIABLE) @Retention(SOURCE) public @interface Cleanup
確保您註解的變數宣告將被清理,透過呼叫其 close 方法,無論發生什麼情況。 實作方式是將局部變數宣告後到您的作用域結束的所有語句,包裝在一個 try 區塊中,該區塊作為 finally 動作,關閉資源。

完整文件請見 project lombok 關於 @Cleanup 的功能頁面

範例

 public void copyFile(String in, String out) throws IOException {
     @Cleanup FileInputStream inStream = new FileInputStream(in);
     @Cleanup FileOutputStream outStream = new FileOutputStream(out);
     byte[] b = new byte[65536];
     while (true) {
         int r = inStream.read(b);
         if (r == -1) break;
         outStream.write(b, 0, r);
     }
 }
 
將產生
 public void copyFile(String in, String out) throws IOException {
     @Cleanup FileInputStream inStream = new FileInputStream(in);
     try {
         @Cleanup FileOutputStream outStream = new FileOutputStream(out);
         try {
             byte[] b = new byte[65536];
             while (true) {
                 int r = inStream.read(b);
                 if (r == -1) break;
                 outStream.write(b, 0, r);
             }
         } finally {
             if (outStream != null) outStream.close();
         }
     } finally {
         if (inStream != null) inStream.close();
     }
 }
 
  • 可選元素摘要

    可選元素
    修飾詞和類型
    可選元素
    描述
     
  • 元素詳細資訊

    • value

      String value
      傳回
      清理資源的方法名稱。預設為 'close'。 該方法不得有任何參數。
      預設
      "close"