【发布时间】:2017-12-12 18:33:27
【问题描述】:
我们正在使用 Java 中的 @Async 注释和 CompletableFutures 对一些调用进行异步处理。我们有许多 Pojo,我们在异步调用中为其创建对象,但是当尝试将结果收集到列表时,Eclipse 希望我将 Pojo 列表更改为对象列表,而我不是了解是否是 CompletableFuture 默认来自流的响应。
List<Pojo1> crudResponse = null;
List<Pojo1> listOfIterations = new ArrayList<>();
//populates object with multiple entries in list
listOfIteration = populateIterationObject(param);
crudResponse = listOfIterations.stream()
.map(str -> CompletableFuture.supplyAsync(() -> {
try {
return async.hitCrud(str);
}catch(RequestProcessingException e){
log.error(e);
}
return function;
}))
.map(CompletableFuture::join)
.collect(Collectors.toList());
}
//async class
public CompletableFuture<Pojo1> hitCrud(Pojo1 iteration) throws RequestProcessingException {
try {
String response;
Pojo1 pojoResponse;
response = connectToCrud(iteration);
if(response != null) {
pojoResponse.add(response);
}
}catch(Exception ex){
log.error(ex);
}
return CompletableFuture.completedFuture(pojoResponse);
}
我点击了返回 Pojo1 对象的方法,但是当我尝试使用 Collectors.toList() 创建一个列表时,它期望我有一个可以使用的 <Object> 列表,但需要更多编码拉出并投射我从异步调用中得到的每个响应。
这是默认为 Object 的 CompletableFuture 吗?如果是这样,是否可以将其默认为 Pojo1 的类型?
编辑: 我在 IDE 中看到的错误:
Type mismatch: cannot convert from List<Object> to List<Pojo1>
【问题讨论】:
-
不,是编辑器弄糊涂了,无法推断出类型。他们有时会这样做。
-
实际上,您似乎确实有一些类型安全问题,但由于您的示例不完整,因此很难确定。我已经能够弥补大部分缺失的位,但
function的类型是什么?
标签: java asynchronous completable-future