Mad*_*osz 3 java try-with-resources autocloseable
我有一个Map<Key, Closeable>
,如果从地图上删除了一个键,我想关闭该Closeable
。通常我有类似的东西:
Closeable c = map.remove(key);
c.close();
Run Code Online (Sandbox Code Playgroud)
我的 Eclipse 警告我“资源 'c' 应该由 try-with-resource 管理”,那么编写以下内容是否更好?
try (Closeable c = map.remove(key)) {}
Run Code Online (Sandbox Code Playgroud)
在我的特殊实现中,我有一个 的子类Closeable
,其中close()
不会抛出IOException
,因此不需要异常处理。
try-with-resources 的要点在于:
Closeable
是在try
语句中完成的try
语句块内close()
自动呼叫您。所以你建议的代码:
try(Closeable c = map.remove(key)) {}
Run Code Online (Sandbox Code Playgroud)
...不满足 try-with-resource 的点,因为您没有使用块内的资源。想必你Closeable
在这个声明之前就已经打开了。
我猜你有一些代码,可以打开一堆资源,完成工作,然后通过地图工作将它们全部关闭。
这是正常的,有时是不可避免的。但如果可能的话,在同一个方法中将open()
和放在一个块中会更干净,这样您一眼就能看到每个都有一个对应的,并且您可以确定始终会调用 。close()
close()
finally
open()
close()
close()
MyCloseable c = MyCloseable.open(...);
try{
// do stuff with c;
} finally {
try {
c.close();
} catch (IOException e) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
一旦你实现了这一点,try-with-resources 只会让事情变得更整洁:
try(MyCloseable c = MyCloseable.open(...)) {
// do stuff with c;
}
Run Code Online (Sandbox Code Playgroud)
如果您的要求意味着您无法使用相同的方法打开和关闭,那么只需坚持使用显式方法close()
并忽略警告即可。
归档时间: |
|
查看次数: |
9856 次 |
最近记录: |