我正在升级一些需要Iterable
s敏感的现有 API AutoCloseable
。例如,给定:
/**
* @throws NoSuchElementException
*/
public static <T> T getOne(Iterable<T> iterable) {
return iterable.iterator().next();
}
如果它是可关闭的,我想要关闭迭代器的方法。这是我到目前为止所得到的:
/**
* @throws NoSuchElementException
*/
public static <T> T getOne(Iterable<T> iterable) {
Iterator<T> iterator = iterable.iterator();
try {
return iterable.iterator().next();
} finally {
if (iterator instanceof AutoCloseable) {
try {
((AutoCloseable) iterator).close();
} catch (Exception ignored) {
// intentionally suppressed
}
}
}
}
鉴于 JDK 文档是如何引用的Throwable.getSuppressed()
,这段代码是否应该做类似于以下的事情?
} catch (Exception x) {
RuntimeException rte = new RuntimeException("Could not close iterator");
rte.addSuppressed(x);
throw rte;
}