适配泛型抛出迭代器的异常类型

问题描述 投票:0回答: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
}

我可以使用适应函数更改迭代器的返回类型,类似于

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
并使用类对象检查它们是否属于预期类型,但这感觉很笨拙。

java exception java-8 interface mapping
1个回答
0
投票

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

很抱歉,这让您感觉很笨重,但这是您唯一的选择。

© www.soinside.com 2019 - 2024. All rights reserved.