gpt4 book ai didi

java - CompletableFutures 带有回调的奇怪行为

转载 作者:行者123 更新时间:2023-12-02 11:38:30 26 4
gpt4 key购买 nike

我想尝试 CompletableFutures 的功能,为此我创建了简单的类 CompletableFutureTests

这是我的方法:

private static String name() {
System.out.println("Name");
return "ALmas";
}

@SneakyThrows(InterruptedException.class)
private static String surname(String name) {
Thread.sleep(2000);
System.out.println("sur");
return name+" Abdrazak";
}

private static String world(String name) {
System.out.println("world");
return name + " hello";
}

private void consumer(String str){
System.out.println("str");
}

private static String onExc(Exception name) {
return "on exception";
}

及用法

CompletableFuture.supplyAsync(CompletableFutureTests::name)
.thenApplyAsync(CompletableFutureTests::surname)
.thenApply(CompletableFutureTests::world)
.thenAccept(CompletableFutureTests::consumer);

这段代码让我困惑

RuntimeException: Uncompilable source code - Erroneous sym type: java.util.concurrent.CompletableFuture.thenAccept

由于这条线

.thenAccept(CompletableFutureTests::consumer)

当我用新类替换它时

private static class Test implements Consumer<String>{

@Override
public void accept(String t) {
System.out.println(t);
}
}

}

CompletableFuture.supplyAsync(CompletableFutureTests::name)
.thenApplyAsync(CompletableFutureTests::surname)
.thenApply(CompletableFutureTests::world)
.thenAccept(new Test());

它按方面工作。正如您所看到的,对 Test 类中的方法 consumer 和方法 apply 的方法引用是相同的

为什么第一个不起作用?

顺便说一句

为什么这个也是正确的

CompletableFuture.supplyAsync(CompletableFutureTests::name)
.thenApplyAsync(CompletableFutureTests::surname)
.thenApply(CompletableFutureTests::world)
.thenAccept(CompletableFutureTests::surname);

(我将对方法姓氏的方法引用传递给 thenAcceptthenAccept 应该将 Consumer 作为参数)

最佳答案

Why first one doesn't work?

它不起作用,因为您的 consumer() 方法不是静态的;您正在提供需要静态方法的实例方法。使其成为静态方法,您的代码就可以工作:

private static void consumer(String str) {
System.out.println("str");
}

BTW Why this one is also correct

(即当所需参数是没有返回值的 Consumer 时,为什么可以成功提供返回值的方法引用?)

您的问题与此问题重复:Why does a Java method reference with return type match the Consumer interface?

特别注意 Brian Goetz 的这些评论:

这是此设计决策的基础:Java 允许您调用方法并忽略返回值(作为语句的方法调用表达式)。由于我们在调用时允许这样做,因此当将方法调整为参数兼容但函数接口(interface)返回 void 的函数接口(interface)时,我们也允许这样做。

另请注意,我们将进行其他调整(装箱、拆箱)以使 lambda 的形状与功能接口(interface)的预期形状相匹配。忽略返回值只是这些调整之一。

另请参阅this answer from Holger :

...设计决策的基础是允许将方法适应功能接口(interface),就像调用该方法一样,即您可以调用每个返回值的方法并忽略返回值。

关于java - CompletableFutures 带有回调的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48743194/

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