抛出异常的Java 8 Lambda函数?

岩石滑轮:

我知道如何创建对具有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);
            }
        };
    

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章