使用try-with-resource遇到的问题

JDK1.7增加了try-with-source语法。在try中声明一个或者多个资源,在try块代码执行完成后自动关闭流,不用再写close()进行手动关闭。

1 try(Resource res = xxx)//可指定多个资源
2 {
3      work with res
4 } 
5 // 实现了AutoCloseable接口的类的对象就是资源

 

于是我想在代码中改成try-with-resource的写法,但是修改后IDEA一直会报编译时错误:

Cannot assign a value to final variable 'connection'

无法给final类型的变量'connection'赋值

后面的statement, resultSet有同样的错误。

于是我去找了一下官方文档,官方文档的try-with-resource中有这样一段描述:

https://docs.oracle.com/javase/specs/jls/se12/html/jls-14.html#jls-14.20.3

It is a compile-time error if final appears more than once as a modifier for each variable declared in a resource specification.

A variable declared in a resource specification is implicitly declared final if it is not explicitly declared final (§4.12.4).

如果final作为资源中声明当前变量的修饰符出现多次,则会出现编译时错误。

在资源中声明的变量如果没有显式声明为final,则将被隐式声明为final。

显然,try-with-resource中声明的变量会被隐式地加上final关键字,所以无法再进行赋值。

因此,对于这种情况我们无法使用try-with-resource.

posted @ 2019-04-10 22:18  NemoWang  阅读(3566)  评论(1编辑  收藏  举报