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;
}