Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用try with resources时,是否也会自动关闭没有引用的资源_Java_Try With Resources - Fatal编程技术网

Java 使用try with resources时,是否也会自动关闭没有引用的资源

Java 使用try with resources时,是否也会自动关闭没有引用的资源,java,try-with-resources,Java,Try With Resources,例如: try(ResultSet rs = DriverManager.getConnection(url, us, pw).createStatement().executeQuery(sql)) { //mycode } 我没有任何关于连接或语句的参考,它们也会关闭吗?如果它们这样做,顺序是什么 谢谢根据,它将只关闭结果集对象。这是因为try with resources语句使用资源规范,其中资源是使用变量声明的: tryWithResources语句: 尝试ResourceS

例如:

try(ResultSet rs = DriverManager.getConnection(url, us, pw).createStatement().executeQuery(sql)) {

    //mycode
}
我没有任何关于
连接
语句
的参考,它们也会关闭吗?如果它们这样做,顺序是什么

谢谢

根据,它将只关闭
结果集
对象。这是因为try with resources语句使用资源规范,其中资源是使用变量声明的:

tryWithResources语句:

尝试ResourceSpecification块[捕获][最终]

ResourceSpecification:

(资源列表[;])

资源列表:

Resource{;Resource}

资源:

{VariableModifier}unnantype VariableDeclaratorId=Expression


有关主题的讨论,请参见此问题:是否正确:通过关闭唯一可用的引用ResultSet rs,我的代码中的资源将自动关闭,这与由其他资源包装的资源类似:new OutputStream(new FileOutputStream())FileOutputStream将通过关闭自动关闭OutputStream@Seyjowzeetaapoogiukaagee不,这是不对的。关闭
ResultSet
不会关闭
语句
,也不会关闭
连接
。那么嵌套流呢?如果try with resource语句close最外层的流是的,通常包装流会自动关闭。