我有两个类,比如说A和B。都返回CompletionStage。
B类代码:

class B {
    public CompletionStage<Optional<Map<String, Object>>> m1(SampleObject1 obj) {
        return CompletableFuture.supplyAsync(() -> dosomething(obj))
            .thenApplyAsync(results ->
                Optional.ofNullable((results.length == 1) ? results : null)
            );
    }
}

A类代码:
class A {
    public CompletionStage<Optional<SampleObject2>> m2(Optional<DynamicForm> dynamicForm) {
        CompletionStage<DynamicForm> promiseOfFormData = CompletableFuture.supplyAsync(() -> dynamicForm.get());

        CompletionStage<Optional<Map<String, Object>>> c = promiseOfFormData.thenApplyAsync(
            data -> b.m1(new SampleObject1(data.get("key1"), data.get("key2")))
        );
        return something.....;
    }
}

但是,它在运行时引发以下错误:
inference variable U has incompatible bounds
    equality constraints: java.util.Optional<java.util.Map<java.lang.String,java.lang.Object>>
    lower bounds: java.util.concurrent.CompletionStage<java.util.Optional<java.util.Map<java.lang.String,java.lang.Object>>>

我在这里做错了什么?

最佳答案

您的退货类型有问题:

b.m1(new SampleObject1(data.get("key1"), data.get("key2")))

CompletionStage<Optional<Map<String, Object>>>中的方法签名返回B,所以
data -> b.m1(new SampleObject1(data.get("key1"), data.get("key2")))

Function<DynamicForm,CompletionStage<Optional<Map<String, Object>>>>类型,以下
promiseOfFormData.thenApplyAsync(
    data -> b.m1(new SampleObject1(data.get("key1"), data.get("key2")))
);

因此是CompletionStage<CompletionStage<Optional<Map<String, Object>>>>类型,与目标CompletionStage<Optional<Map<String, Object>>>类型不兼容。您的错误在于目标类型边界的计算中。

相反,您应该使用 CompletionStage#thenComposeAsync ,它是为也返回CompletionStage的函数设计的:
CompletionStage<Optional<Map<String, Object>>> c = promiseOfFormData.thenComposeAsync(
    data -> b.m1(new SampleObject1(data.get("key1"), data.get("key2")))
);

或者,您可以重写m1而不创建CompletionStage,而只是执行计算,然后像以前一样在thenApplyAsync调用中使用它。

10-06 15:03