源碼分析(三)-AutoCloseable源碼分析

AutoCloseable

該接口用於try-with-resources語法糖提供支持,用於自動關閉資源做用code

  1. 類型:接口
  2. 方法:close();
  3. 詳解:
  • close():用於自動關閉資源的時候須要進行調用該方法,該方法聲明中設置了拋出Exception異常
  1. 注意事項:
    1. 雖然其拋出的Exception異常,可是在註釋上說明了最好不要在代碼中拋出中斷異常(InterruptedException),也就是說須要對中斷類型的異常進行捕獲
    2. 因爲基本上子類實現的close方法最後調用的基本上都是本地方法。

例子:接口

public class AutoCloseableTest {
    @Test
    public void test(){
        try(FileInputStream inputStream=new FileInputStream(new File("test.txt"))){
            //do somethings 
        } catch (IOException e) {
            e.printStackTrace();
        }
        //不須要在使用finally去關閉資源了,方便快捷
    }

}
相關文章
相關標籤/搜索