You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java代码模块化优化:如何一行校验多个getter返回值是否全为null

一行校验所有属性全为null的实现

Java 8及以上版本可以直接用Stream流实现一行校验,代码如下:

boolean allFieldNull = Stream.of(rule.getDescription(), rule.getName(), rule.getScript(), rule.getTargets(), rule.getTrigger()).allMatch(Objects::isNull);

如果是不支持Stream的低Java版本,也可以直接用逻辑运算符拼接实现一行校验:

boolean allFieldNull = rule.getDescription() == null && rule.getName() == null && rule.getScript() == null && rule.getTargets() == null && rule.getTrigger() == null;
整体代码优化方案

场景1:需要给所有非空属性赋值(常规更新场景,修正原if-else if仅赋值第一个非空属性的逻辑)

这是绝大多数更新场景的需求,只要属性非空就覆盖到ruleBean的对应字段,代码更简洁易读:

// 先校验所有字段全为空的情况,直接返回错误
if (Stream.of(rule.getDescription(), rule.getName(), rule.getScript(), rule.getTargets(), rule.getTrigger()).allMatch(Objects::isNull)) {
    return ResponseBean.builder().withData(request.getData())
            .withMessage("No data provided for rule update").asFailure().build();
}
// 逐个赋值非空字段
Optional.ofNullable(rule.getDescription()).ifPresent(ruleBean::setDescription);
Optional.ofNullable(rule.getName()).ifPresent(ruleBean::setName);
Optional.ofNullable(rule.getScript()).ifPresent(ruleBean::setScript);
Optional.ofNullable(rule.getTargets()).ifPresent(ruleBean::setTargets);
Optional.ofNullable(rule.getTrigger()).ifPresent(ruleBean::setTrigger);

如果项目引入了Spring等框架,也可以直接用工具类实现非空属性拷贝,进一步简化代码:

// 调用工具类仅拷贝source中不为null的属性到目标对象
BeanUtils.copyProperties(rule, ruleBean, getNullPropertyNames(rule));

场景2:保留原逻辑仅赋值第一个非空属性

如果业务确实需要按优先级只赋值第一个非空的属性,可以用如下写法实现:

Optional<Map.Entry<Object, Consumer<Object>>> firstNonNullOpt = Stream.of(
    new AbstractMap.SimpleEntry<>(rule.getDescription(), (Consumer<Object>) ruleBean::setDescription),
    new AbstractMap.SimpleEntry<>(rule.getName(), (Consumer<Object>) ruleBean::setName),
    new AbstractMap.SimpleEntry<>(rule.getScript(), (Consumer<Object>) ruleBean::setScript),
    new AbstractMap.SimpleEntry<>(rule.getTargets(), (Consumer<Object>) ruleBean::setTargets),
    new AbstractMap.SimpleEntry<>(rule.getTrigger(), (Consumer<Object>) ruleBean::setTrigger)
).filter(entry -> entry.getKey() != null).findFirst();

if (firstNonNullOpt.isEmpty()) {
    return ResponseBean.builder().withData(request.getData())
            .withMessage("No data provided for rule update").asFailure().build();
}
firstNonNullOpt.get().getValue().accept(firstNonNullOpt.get().getKey());

内容的提问来源于stack exchange,提问作者Doyel Mishra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 01:18:01