源码分析(三)-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去关闭资源了,方便快捷
    }

}
相关文章
相关标签/搜索