CompletableFuture 对象数组的空检查
Null check for CompletableFuture Object Array
我正在为我的一项服务使用 CompletableFuture,如下所示 -
CompletableFuture<Employee>[] employeeDetails =
empIds.stream().map(empId ->
employeeService.employeeDetails(Integer.valueOf(empId))).toArray(CompletableFuture[]::new);
内部 EmployeeService 调用 API 其中 returns 员工详细信息。
问题是当 API returns 为空或任何异常时响应为空。当我检查 null 时,即使 employeeDetails 数组为 null 并且它的值也为 null 并且我得到 Null Pointer.
我检查 null 为 -
if(employeeDetails != null && employeeDetails.length > 0){
//This condition always true even if null values or null array.
CompletableFuture<Void> allEmployeeDetails = CompletableFuture.allOf(employeeDetails); // Here I am getting NullPointerException
}
我在这里犯了什么错误,或者 CompletableFuture 数组需要进行任何特殊检查。
嗯,CompletableFuture.allOf(employeeDetails)
抛出
NullPointerException if the array or any of its elements are null
您必须检查数组的所有元素,并且只将非空元素传递给allOf
。
或者您可以在创建数组之前过滤掉 null
:
CompletableFuture<Employee>[] employeeDetails =
empIds.stream()
.map(empId -> employeeService.employeeDetails(Integer.valueOf(empId)))
.filter(Objects::nonNull)
.toArray(CompletableFuture[]::new);
这样你的 if
语句就足够了。
我正在为我的一项服务使用 CompletableFuture,如下所示 -
CompletableFuture<Employee>[] employeeDetails =
empIds.stream().map(empId ->
employeeService.employeeDetails(Integer.valueOf(empId))).toArray(CompletableFuture[]::new);
内部 EmployeeService 调用 API 其中 returns 员工详细信息。
问题是当 API returns 为空或任何异常时响应为空。当我检查 null 时,即使 employeeDetails 数组为 null 并且它的值也为 null 并且我得到 Null Pointer.
我检查 null 为 -
if(employeeDetails != null && employeeDetails.length > 0){
//This condition always true even if null values or null array.
CompletableFuture<Void> allEmployeeDetails = CompletableFuture.allOf(employeeDetails); // Here I am getting NullPointerException
}
我在这里犯了什么错误,或者 CompletableFuture 数组需要进行任何特殊检查。
嗯,CompletableFuture.allOf(employeeDetails)
抛出
NullPointerException if the array or any of its elements are null
您必须检查数组的所有元素,并且只将非空元素传递给allOf
。
或者您可以在创建数组之前过滤掉 null
:
CompletableFuture<Employee>[] employeeDetails =
empIds.stream()
.map(empId -> employeeService.employeeDetails(Integer.valueOf(empId)))
.filter(Objects::nonNull)
.toArray(CompletableFuture[]::new);
这样你的 if
语句就足够了。