gpt4 book ai didi

抛出异常的Java 8 Lambda函数?

转载 作者:bug小助手 更新时间:2023-10-28 01:36:00 25 4
gpt4 key购买 nike

我知道如何创建对具有 String 参数并返回 int 的方法的引用,它是:

Function<String, Integer>

但是,如果函数抛出异常,这将不起作用,假设它被定义为:

Integer myMethod(String s) throws IOException

我将如何定义这个引用?

最佳答案

您需要执行以下操作之一。

  • 如果是你的代码,那么定义你自己的函数式接口(interface)来声明被检查的异常:

    @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);
    }
    };

关于抛出异常的Java 8 Lambda函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18198176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com