假设我要实现一个java.util.function.Function<T,R>
可以抛出某些异常类型的版本E
。我所做的是创建一个功能接口,ThrowingFunction
如下所示:
@FunctionalInterface
interface ThrowingFunction<T, R, E extends Exception>
{
R apply(T t) throws E;
}
现在就像在中一样java.util.function.Function<T,R>
,我需要实现默认方法,compose
并且我需要组成两个不同的ThrowingFunction
实例,并且可能,它们可以具有不同的抛出异常类型。所以这是我的尝试:
default <V, E1 extends Exception, E2 super E1 & E> ThrowingFunction<V, R, E2> compose(ThrowingFunction<? super V, ? extends T, ? extends E1> before)
{
return v -> apply(before.apply(v));
}
当然,在这里,我得到了一个编译器错误,说:
令牌“ super”上的语法错误,预期扩展
恰好在通用参数的声明中E2 super E1 & E
。
那么,该问题的可能解决方案是什么,我是否只需编写两个ThrowingFunction
具有相同异常类型的不同实例E
(而这不是最好的)?
您不能default
在此处使用方法;它必须是static
接口上的方法。当您尝试使用default
方法时,类型E
已经被捕获,并且Java编译器不允许您将类型声明为E2
2类E
和以下的超类E1
,这是编译器错误指示的。
更改为static
方法时,可以根据需要自由声明异常类型参数。您可以声明超类型异常类型S
,然后声明子类型异常类型E1
和E2
。然后其余的内容与Function
的默认compose
方法类似。
此处的类型参数与Function.compose
使用的内容匹配,并添加了与异常相关的类型参数。
@FunctionalInterface
interface ThrowingFunction<T, R, E extends Exception>
{
R apply(T t) throws E;
/**
* Composes f (after) and g (before) to produce the composed
* function f o g(v), which executes f(g(v)).
* @param f The function that will take g's output <T> as input to return the overall result <R>.
* @param g The function that will take the overall input <V> and return f's input <T>.
* @param <V> The input result type of the entire composed function (and of function g).
* @param <T> The result type of g, used as input to f.
* @param <R> The end result type of the entire composed function (and of function f).
* @param <S> If any of f or g throws an exception, it is captured by the supertype exception class S.
* @param <E1> The exception type thrown by f.
* @param <E2> The exception type thrown by g.
* @return A ThrowingFunction that whose input <V> is applied to g, whose result is passed to
* f to generate the overall result <R>.
*/
static <V, T, R, S extends Exception, E1 extends S, E2 extends S> ThrowingFunction<V, R, S>
compose(ThrowingFunction<? super T, ? extends R, ? extends E1> f,
ThrowingFunction<? super V, ? extends T, ? extends E2> g)
{
return v -> f.apply(g.apply(v));
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句