我知道如何创建一个方法的引用,该方法有一个String
参数,返回一个int
,它是:
Function<String, Integer>
但是,如果函数抛出异常,这将不起作用,比如它被定义为:
Integer myMethod(String s) throws IOException
我该如何定义这个引用呢?
我知道如何创建一个方法的引用,该方法有一个String
参数,返回一个int
,它是:
Function<String, Integer>
但是,如果函数抛出异常,这将不起作用,比如它被定义为:
Integer myMethod(String s) throws IOException
我该如何定义这个引用呢?
您需要执行以下操作之一.
如果是你的代码,那么定义你自己的函数接口来声明选中的异常:
@FunctionalInterface
public interface CheckedFunction<T, R> {
R apply(T t) throws IOException;
}
并使用它:
void foo (CheckedFunction f) { ... }
否则,将Integer myMethod(String s)
包装在不声明判断异常的方法中:
public Integer myWrappedMethod(String s) {
try {
return myMethod(s);
}
catch(IOException e) {
throw new UncheckedIOException(e);
}
}
然后:
Function<String, Integer> f = (String t) -> myWrappedMethod(t);
或者:
Function<String, Integer> f =
(String t) -> {
try {
return myMethod(t);
}
catch(IOException e) {
throw new UncheckedIOException(e);
}
};