代码之家  ›  专栏  ›  技术社区  ›  EarthTurtle

调整泛型抛出迭代器的异常类型

  •  0
  • EarthTurtle  · 技术社区  · 1 年前

    我有一个界面 ThrowingIterator ,遵循通用合同 Iterator ,除了 hasNext() next() 方法可以抛出异常:

    public interface ThrowingIterator<T, E extends Throwable> {
      boolean hasNext() throws E;
      T next() throws E;
      default void remove() throws E { /* throw unsupported */ }
      // forEachRemaining same as Iterator
    }
    

    我可以使用adapt函数更改迭代器的返回类型,类似于 Stream map(Function<? super T, U> mapper) 然而,我还没有找到一种方法来更改迭代器的异常类型,如下所示:

    // example method
    default <X extends Throwable> ThrowingIterator<T, X> adaptException(Function<? super E, ? extends X> exceptionMapper) {
      return new ThrowingIterator<T, X> {
        public boolean hasNext() {
          try {
            return this.hasNext();
          } catch (E e) { // this does not work, can't catch E
            throw exceptionMapper.apply(e);
          }
        }
      }
      // same for next()
    }
    
    // example use
    ThrowingIterator<Integer, IOException> baseIterator = getIterator();
    ThrowingIterator<Integer, ExecutionException> adaptedIterator = baseIterator.adaptException(ExecutionException::new);
    

    编写此函数的主要困难在于Java不允许捕获泛型异常类型。有没有办法绕过这个限制?我能抓住一切 Throwable s,并使用类对象检查它们是否是预期的类型,但这感觉很笨拙。

    1 回复  |  直到 1 年前
        1
  •  2
  •   Louis Wasserman    1 年前

    我可以捕获所有Throwable,并使用类对象检查它们是否是预期的类型,但这感觉很笨拙。

    很抱歉,这对你来说很笨重,但这是你唯一的选择。

        2
  •  0
  •   ControlAltDel    1 年前

    以下是我将如何做到这一点(这是基于我在DataFetcher上的工作( https://sourceforge.net/p/tus/code/HEAD/tree/tjacobs/io/DataFetcher.java )多年前)

    public interface ThrowingIterator<T,E> extends Iterator<T> {
      // because this extends Iterator, the client must implement those methods as well
      void exceptionOccurred(E e);
    }
    

    现在,客户端有一个特定的方法来实现,以处理迭代过程中出现错误的情况。