美文网首页
JDK11都有了,可我们连JDK7的try-with-resou

JDK11都有了,可我们连JDK7的try-with-resou

作者: 僧唐 | 来源:发表于2018-12-27 13:20 被阅读0次

经常看到网上有很多关于JDK关于 lamda,nio,等版本更新的说明,但可能我们连try-catch的使用都不会
从Java 7 开始编译器和运行环境支持新的 try-with-resources 语句,称为 ARM 块(Automatic Resource Management) ,自动资源管理。
不多说,举个栗子:
Connection conn=null;
try{
conn=DriverManager.getConnection(.....);
stmt=conn.prepareStatement(..);
}catch(Exception ex){
//。。。
throw new XXXException(...,e);
}finally{
try{
if(stmt!=null){
stmt.close()
}
}
}

如果用 try-with-resources 可以写成
try(Connection conn=.... ;
stmt=conn.prepareStatement;
){
}catch(){
}
不再需要finally.
那JDK是按照什么规则 进行关闭的呢? JDK会查询try()中的对象类型是否 implements AutoClosable。

相关文章

网友评论

      本文标题:JDK11都有了,可我们连JDK7的try-with-resou

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