源码分析-AutoCloseable


AutoCloseable

该接口用于try-with-resources语法糖提供支持,用于自动关闭资源作用

  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去关闭资源了,方便快捷
    }

}

  

原文地址:https://www.cnblogs.com/lonecloud/p/9102948.html