在设置变量之前检查 null - 没有 if-else

我用来从一个对象Lombok-Builder构建我的apijava对象entity

RewardApi.builder()
                .rewardId(rewardEntity.getrewardId())
                .rewardTitle(rewardEntity.getrewardTitle())
                .rewardText(rewardEntity.getrewardText())
                .rewardFor(rewardEntity.getrewardFor())
                .rewardType(rewardEntity.getrewardType())
                .rewardFromDate(rewardEntity.getrewardFromDate().toZonedDateTime())
                .rewardToDate(rewardEntity.getrewardToDate().toZonedDateTime())
                .isDisplayOn(rewardEntity.getIsDisplayOn())
                .createdId(rewardEntity.getCreatedId())
                .updatedId(rewardEntity.getUpdatedId())
                .createdDate(rewardEntity.getCreatedDate().toZonedDateTime())
                .lastModifiedDate(rewardEntity.getLastModifiedDate().toZonedDateTime())
                .build();

我正在nullPointerException设置lastModifiedDate字段,因为entity对象正在获取该字段,并且正在null执行toZonedDateTime()null

如何在没有传统方式(如下所述)的情况下解决这个问题

if (null!=rewardEntity.getLastModifiedDate(){....}

我想在null使用设置变量时进行检查,builder-pattern而不是null在构建对象后进行检查。无论如何 ?



GCT1015
浏览 108回答 3
3回答

qq_遁去的一_1

所有的孩子都喜欢Optional这些日子:Optional.ofNullable(rewardEntity.getLastModifiedDate())     .map(r -> r.toZonedDateTime())     .orElse(null) // or some other default value

jeck猫

rewardEntity.getLastModifiedDate() != null ? rewardEntity.getLastModifiedDate().toZonedDateTime() : null它被称为条件运算符,它是一个三元运算符,因为它具有三个操作数。

隔江千里

你可以有一个通用的实用方法来处理空情况,比如static <T, R> R transform(T obj, Function<T, R> function) {&nbsp; &nbsp; return obj != null ? function.apply(obj) : null;}并按如下方式使用.rewardToDate(transform(rewardEntity.getRewardToDate(), OffsetDateTime::toZonedDateTime))实际上更好的是“覆盖” lombok 构建器方法,因为您现在拥有的看起来更像是占位符/DTO 而不是构建器:@Builderprivate static class RewardApi {&nbsp; &nbsp; //...&nbsp; &nbsp; private ZonedDateTime rewardToDate;&nbsp; &nbsp; public static class RewardApiBuilder {&nbsp; &nbsp; &nbsp; &nbsp; public RewardApiBuilder rewardToDate(OffsetDateTime offsetDateTime) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(offsetDateTime != null) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.rewardToDate = offsetDateTime.toZonedDateTime();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return this;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java