Vic*_*res 6 java java-8 option-type
null我有一个可为空的对象,如果该对象不满足且不满足条件,我将尝试抛出异常。
我尝试用以下方法Optional:
Optional.ofNullable(nullableObject)
.filter(object -> "A".equals(object.getStatus()))
.orElseThrow(() -> new BusinessUncheckedException("exception message"));
Run Code Online (Sandbox Code Playgroud)
当对象不是 时null,它会按我想要的方式工作,但否则,它也会引发异常(我不希望这样)。
有一种方法可以做到这一点,Optional或者有其他方法不使用if object != null?
假设您没有对返回的对象执行任何操作,您可以使用ifPresent并传递Consumer
nullableObject.ifPresent(obj -> {
if (!"A".equals(obj.getStatus())) {
throw new BusinessUncheckedException("exception message");
}
});
Run Code Online (Sandbox Code Playgroud)
注意:正如 @Pshemo 在评论中提到的,函数式接口的约定Consumer仅允许抛出 RuntimeExceptions。
否则,您最好像您提到的那样进行if检查。
IMO,使用filteronOptional 进行此类检查不是那么可读/直观。我会比较喜欢,
if (obj != null && !"A".equals(obj.getStatus())) {
throw new BusinessUncheckedException("exception message");
}
Run Code Online (Sandbox Code Playgroud)