zoukankan      html  css  js  c++  java
  • 使用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.

  • 相关阅读:
    dos命令积累
    bt的SoundMixerl类
    给自己一个定位
    自我的反思
    计算机爱好者 VS. 程序员
    flash实现bt传输方式
    flash获取不到页面传进来的参数的一种情况
    教程:深入理解Flash的沙箱 – Application Domains
    使用URLLoader做上传出现的问题
    原创系列之:Flex数据绑定基础介绍[转]
  • 原文地址:https://www.cnblogs.com/nemowang1996/p/10686589.html
Copyright © 2011-2022 走看看