如何不抛出一般指定的异常? [英] How to not throw a generically specified exception?
问题描述
我创建了一个生产者界面(与方法引用一起使用,分别用于单元测试的模拟):
I created a "producer" interface (to be used with method references, respectively to be easily mocked for unit tests):
@FunctionalInterface
public interface Factory<R, T, X extends Throwable> {
public R newInstanceFor(T t) throws X;
}
我是这样创建的,因为我的第一个用例实际上必须抛出一些选中 WhateverException
。
which I created like that, as my first use case actually had to throw some checked WhateverException
.
但我的第二个用例没有投掷X.
But my second use case doesn't have an X to throw.
我能想出的让编译器满意的最好方法是:
The best I could come up with to make the compiler happy is:
Factory<SomeResultClass, SomeParameterClass, RuntimeException> factory;
编译,做我需要的,但仍然很难看。有没有办法保留单个接口,但在声明特定实例时不提供X?
That compiles, and does what I need, but still ugly. Is there a way to keep that single interface, but not provide an X when declaring specific instances?
推荐答案
唯一的办法它是子类 - 但我打赌你知道这一点。为了使我的论证更强大,请查看扩展 BiFunction
的 BinaryOperator
。
The only way to do it is subclassing - but I bet you knew that. To make my argument stronger, look at BinaryOperator
that extends BiFunction
.
这篇关于如何不抛出一般指定的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!