WebFlux中处理可空字段消除空值警告的其他方案咨询
问题
我定义了一个包含可为空字段的简单DTO:
public class ResponseDto{ // ... @Nullable public List<ListDto> getListDto() { return this.listDto; } // ... }
在下面这个返回@NotNull修饰的Flux<ListDto>的方法中,我需要通过正确的空值检查消除IDE警告(警告提示:在转换方法的lambda中返回null或可为空的内容,指向map(ResponseDto::getListDto)这一行):
@NotNull public Flux<ListDto> getApplicationList(String applicationSubsidiesId) { return Mono.fromCallable(() -> mapper.toRq(applicationSubsidiesId)) .subscribeOn(Schedulers.boundedElastic()) .flatMap(subsidiesClient::getResponseById) .filter(responseDto -> Objects.nonNull(responseDto.getListDto())) .map(ResponseDto::getListDto) // 此处触发警告 .flatMapMany(Flux::fromIterable); }
我目前的一种解决方式是改写map操作:
.map(responseDto -> Objects.requireNonNull(responseDto.getListDto()))
请问还有哪些正确实现空值检查以消除警告的方案?
解决方案
以下是几种可行的方案,都能有效消除空值警告并保证代码安全性:
1. 合并过滤与转换逻辑到flatMap
直接在flatMap中处理空值判断,省去单独的filter和map操作,逻辑更紧凑:
@NotNull public Flux<ListDto> getApplicationList(String applicationSubsidiesId) { return Mono.fromCallable(() -> mapper.toRq(applicationSubsidiesId)) .subscribeOn(Schedulers.boundedElastic()) .flatMap(subsidiesClient::getResponseById) .flatMap(responseDto -> { List<ListDto> list = responseDto.getListDto(); return list != null ? Flux.fromIterable(list) : Flux.empty(); }); }
2. 使用Optional包装并链式转换
利用Optional的API明确处理空值,让编译器清晰识别非空分支:
@NotNull public Flux<ListDto> getApplicationList(String applicationSubsidiesId) { return Mono.fromCallable(() -> mapper.toRq(applicationSubsidiesId)) .subscribeOn(Schedulers.boundedElastic()) .flatMap(subsidiesClient::getResponseById) .flatMapMany(responseDto -> Optional.ofNullable(responseDto.getListDto()) .map(Flux::fromIterable) .orElseGet(Flux::empty) ); }
3. 静态导入Objects.requireNonNull简化代码
和你当前的方案原理一致,通过静态导入让代码更简洁,同时明确告知编译器此处无空值:
import static java.util.Objects.requireNonNull; import static java.util.Objects.nonNull; // ... @NotNull public Flux<ListDto> getApplicationList(String applicationSubsidiesId) { return Mono.fromCallable(() -> mapper.toRq(applicationSubsidiesId)) .subscribeOn(Schedulers.boundedElastic()) .flatMap(subsidiesClient::getResponseById) .filter(responseDto -> nonNull(responseDto.getListDto())) .map(responseDto -> requireNonNull(responseDto.getListDto())) .flatMapMany(Flux::fromIterable); }
4. 依赖Project Lombok的校验(若项目已引入)
如果项目使用Lombok,可以直接用其提供的@NonNull校验工具(效果和Objects.requireNonNull类似):
import static lombok.Lombok.requireNonNull; // ... .map(responseDto -> requireNonNull(responseDto.getListDto()))
内容的提问来源于stack exchange,提问作者Aliaksei
相关产品推荐
相关产品推荐

