使用 try-with-resources 时,没有引用的资源是否也会自动关闭
Are the resources without reference automatically closed too while using try-with-resources
示例:
try(ResultSet rs = DriverManager.getConnection(url, us, pw).createStatement().executeQuery(sql)) {
//mycode
}
我没有提到 Connection
或 Statement
,它们也会被关闭吗?如果他们这样做,顺序是什么?
谢谢
根据language specification,它只会关闭ResultSet
对象。这是因为 try-with-resources 语句使用资源规范,其中使用变量声明资源:
TryWithResourcesStatement:
try ResourceSpecification Block [Catches] [Finally]
ResourceSpecification:
( ResourceList [;] )
ResourceList:
Resource {; Resource}
Resource:
{VariableModifier} UnannType VariableDeclaratorId = Expression
示例:
try(ResultSet rs = DriverManager.getConnection(url, us, pw).createStatement().executeQuery(sql)) {
//mycode
}
我没有提到 Connection
或 Statement
,它们也会被关闭吗?如果他们这样做,顺序是什么?
谢谢
根据language specification,它只会关闭ResultSet
对象。这是因为 try-with-resources 语句使用资源规范,其中使用变量声明资源:
TryWithResourcesStatement:
try ResourceSpecification Block [Catches] [Finally]
ResourceSpecification:
( ResourceList [;] )
ResourceList:
Resource {; Resource}
Resource:
{VariableModifier} UnannType VariableDeclaratorId = Expression