猿问

为 Runnable 包装 Lambda 表达式以处理异常

我正在尝试初始化一个 Runnable 数组,然后运行它们的代码。我需要初始化尽可能具有可读性,因此我为此使用了 Lambda 表达式。现在我不知道如何解决异常问题。如果 Runnables 中的某些代码抛出已检查的异常,我想将其自动包装到 RuntimeException 中,但不将 try/catch 逻辑放入每个 Runnable 主体中。


代码如下所示:


public void addRunnable(Runnable ... x); // adds a number of Runnables into an array

...

addRunnable(

   ()->{

       some code;

       callMethodThrowsException();  // this throws e.g. IOException

   },


   ()->{

       other code;

   }

   // ... and possibly more Runnables here

);


public void RunnableCaller(List<Runnable> runnables) {

    // Now I want to execute the Runnables added to the array above

    // The array gets passed as the input argument "runnables" here

    for(Runnable x: runnables) {

        try {

            x.run();

        } catch(Exception e) { do some exception handling }

    }

}

代码无法编译,因为 callMethodThrowsException 抛出了一个已检查的异常,而 Runnable 没有,所以我必须在 Runnable 定义的内部插入一个 try/catch 块。try/catch 块会使这件事变得不那么方便,因为我必须将它放入每个 Runnable 主体声明中,这将难以阅读且编写起来令人不快。我也可以创建自己的 Runnable 类来抛出异常,但是我不能使用 Lambda 表达式 ()-> 这使得它简短易读而不是做


new ThrowingRunnable() { public void run() throws Exception { some code; } }

有没有办法定义我自己的功能接口来解决这个问题,以便我可以使用相同的代码,但异常将被包装到例如 RuntimeExceptions 等中?我可以完全控制调用代码,因此在那里捕获异常没有问题,我只需要一种非常易读的编写稍后将执行的代码的方式。


我看到了这个话题抛出异常的 Java 8 Lambda 函数?但我没有想出如何解决我的问题,我对功能接口不是很熟悉。可能有人可以帮忙,谢谢。


郎朗坤
浏览 196回答 1
1回答

翻过高山走不出你

Lambda 不仅用于 JVM 提供的接口。它们可用于精确定义一个且仅一个抽象方法的每个接口。所以你可以自己创建一个接口,你已经命名了它:public interface ThrowingRunnable{&nbsp; &nbsp; void run() throws Exception;}然后替换方法中的Parameter类型addRunnable:public void addRunnable(ThrowingRunnable... runnables){ ... }然后让这个编译:addRunnable(&nbsp; &nbsp;()->{&nbsp; &nbsp; &nbsp; &nbsp;some code;&nbsp; &nbsp; &nbsp; &nbsp;callMethodThrowsException();&nbsp; // this throws e.g. IOException&nbsp; &nbsp;},&nbsp; &nbsp;()->{&nbsp; &nbsp; &nbsp; &nbsp;other code;&nbsp; &nbsp;}&nbsp; &nbsp;// ... and possibly more Runnables here);
随时随地看视频慕课网APP

相关分类

Java
我要回答