Java 8 Optional 只对存在的元素进行过滤。

6

我有一个可空对象,并且如果该对象不为null且不满足某些条件,我希望抛出异常。

我使用Optional尝试以下方式:

Optional.ofNullable(nullableObject)
    .filter(object -> "A".equals(object.getStatus()))
    .orElseThrow(() -> new BusinessUncheckedException("exception message"));

当对象不为 null 时,它按照我的预期工作,但是当对象为 null 时,它也会抛出异常(我不想要这种情况)。

是否有使用 Optional 或其他方式而不使用 if object != null 的方法来解决这个问题?

2个回答

7

假设您不对返回的对象进行任何操作,您可以使用 ifPresent 并传递一个 Consumer

nullableObject.ifPresent(obj -> {
    if (!"A".equals(obj.getStatus())) {
        throw new BusinessUncheckedException("exception message");
    }
});

注意: 正如评论中@Pshemo所提到的,Consumer函数接口的契约仅允许抛出RuntimeException异常。

否则,最好像您已经提到的那样使用if检查。

在我看来,对于这些检查,使用Optional的filter并不那么可读/直观。我更喜欢以下方式:

if (obj != null && !"A".equals(obj.getStatus())) {     
    throw new BusinessUncheckedException("exception message");
}

1
如果你将map映射为null,Optional 就会变为空:
Optional.ofNullable(nullableObject)
    .map(object -> "A".equals(object.getStatus()) ? object : null)
    .ifPresent(object -> { throw new BusinessUncheckedException("exception message"); });

我没有测试过,但我认为当对象为空时,它会抛出一个NullPointerException异常。(object.getStatus...) - Victor Soares
@VictorSoares 的 object 永远不会为空。 - Andy Turner
好的,你是对的。但是它仍然会抛出BusinessUncheckedException异常。 - Victor Soares
如果nullableObjectnull,则OP不想抛出异常。规则是它可以为null - 或者如果不为null,则其getStatus必须为A - Thiyagu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接