在 CompletableFuture 中执行不同签名的方法

从下面的代码中,我想foo3在. 的方法签名无法更改。一种方法是进入,但这会破坏关注点分离。foo2foo1foo1foo3foo2


@Override

CompletableFuture<Integer> foo1(String str) {

    return CompletableFuture.supplyAsync(() -> foo2(str));

}


Integer foo2(String str) {

    return 0;

}


void foo3(String str) {

    System.out.println("Done");

}


忽然笑
浏览 125回答 3
3回答

拉莫斯之舞

假设您只想调用foo3afterfoo2并返回foo2输出,那么您可以这样做:return CompletableFuture.supplyAsync(() -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Integer r = foo2(str);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foo3("testing");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return r;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; );

慕婉清6462132

如果foo3call 应该是 的一部分foo1,那么这是一种方法:CompletableFuture<Integer> foo1(String str) {&nbsp; &nbsp; return CompletableFuture.supplyAsync(() -> foo2(str))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .thenApply(foo2Result -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foo3(str);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return foo2Result;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; );}或者如果你想调用它,在foo1调用的地方:foo1(str).thenApply(result -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; foo3(str);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return result;&nbsp; &nbsp; &nbsp; &nbsp; });

汪汪一只猫

你的意思是像foo1(str).thenRun(()&nbsp;->&nbsp;foo3(str);foo1因为你似乎对的结果不感兴趣。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java