[英]Array or collection of “Autocloseable” in Java8
Autocloseable
应始终与try-with-resources
。 至少Intellij检查表明了这一点。 所以,如果我有一个产生Foo
的代码来实现Autocloseable
我应该这样做:
try (final Foo foo = getFoo()) {
foo.doSomething();
}
但是,如果我有返回Foo[]
函数怎么办? 或者接受Foo[]
(或Collection<Foo>
)作为参数的函数?
如何在try-with-resources
使用它? 查看以下功能:
Foo[] getFoos();
doAll(Foo... foo);
我想做一些行doAll(getFoos())
我怎样才能做到这一点?
Try-with-resources语句只能关闭在其标头中声明和分配的那些资源。 所以唯一的方法是让你得到的集合实现AutoCloseable或将它包装到你的AutoCloseable扩展中,所以它的close()方法将由TWR调用。 喜欢:
try (SomeAutoCloseableCollction col = getAutoCloseables()) {
System.out.println("work");
} //col.close() gets called
对于一个数组,我担心没有办法,因为你无法扩展它并使它实现一些接口。
如果您要自己关闭收集,可以查看Apache Drill项目和类org.apache.drill.common.AutoCloseables
- 它就是这样做,自己关闭大量的AutoCloseables。
您可以创建将AutoCloseable
组合为单个方法的方法,这些方法将安全地关闭所有方法:
public static AutoCloseable closeBoth(AutoCloseable a, AutoCloseable b) {
if(a==null) return b;
if(b==null) return a;
return () -> { try(AutoCloseable first=a) { b.close(); } };
}
public static AutoCloseable closeAll(AutoCloseable... c) {
return Arrays.stream(c).reduce(null, MyClass::closeBoth);
}
它们允许使用数组返回方法
Foo[] foo;
try(AutoCloseable closeAll = MyClass.closeAll(foo=getFoos())) {
/*
use foo
*/
}
正如另一个答案所说,这是不可能的。 但是,您应该问自己为什么需要将整个集合放在AutoCloseable中。 如果要确保每个元素在处理后关闭,您可以执行以下操作:
Foo[] foos = getFoos();
for (int i = 0; i < foos.length; i++) {
try (Foo foo = foos[i]) {
// Your code here
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.