美文网首页Java
【Java高级】使用try-with-resources语句自动

【Java高级】使用try-with-resources语句自动

作者: 大栗几 | 来源:发表于2020-05-25 22:35 被阅读0次

本文为原创文章,转载请注明出处
查看[Java]系列内容请点击:https://www.jianshu.com/nb/45938443

在Java7以前,对于需要关闭的资源,我们写异常捕获的代码通常如下:

AutoCloseable resource = new YourClass(...);
try{
  ...
} catch (Exception e) {
  ...
} finally {
  try {
    resource.close();
  } catch (Exception e1) {
    ...
  }
}

是不是很麻烦,就光关闭资源的代码就写了这么多行?

从Java7开始,提供了try-with-resources语句,可以改下如下:

try(AutoCloseable resource = new YourClass(...)) {
 ...
} catch (Exception e) {
 ...
}

try完毕后,会自动关闭resource

还可以指定关闭多个资源:

try(AutoCloseable resource = new YourClass(...);
      AutoCloseable resource1 = new YourClass(...)) {
 ...
}

try完毕后resourceresource1都会自动关闭。

注意:前提是YourClass必需继承自AutoCloseable

从Java9开始,也可以关闭外部声明的事实最终变量:

public static void test(AutoCloseable resource) {
  try(resource) {
  ...
  }...
}

如果你不想一遍遍的手动关闭资源,就试试这种方式吧~

相关文章

网友评论

    本文标题:【Java高级】使用try-with-resources语句自动

    本文链接:https://www.haomeiwen.com/subject/nqfpahtx.html