1

我正在升级一些需要Iterables敏感的现有 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;
      }
4

1 回答 1

3

我认为最好的办法就是简单地背负try-with-resources结构,如果你发现你有一个AutoCloseable,像这样:

/**
 * @throws NoSuchElementException
 */
public static <T> T getOne(Iterable<T> iterable) {
  Iterator<T> iterator = iterable.iterator();
  if (iterator instanceof AutoCloseable) {
    try (AutoCloseable c = (AutoCloseable) iterator) {
      return iterator.next();
    }
  } else {
    return iterator.next();
  }
}

然后语言级构造将以close正确的方式处理异常(包括在方法中)。

于 2014-05-07T22:05:23.567 回答