繁体   English   中英

java可选检查null

[英]java Optional checking nulls

我的印象是Optional.ofNullable(response.getSubscriber())也可以确定对象的响应是否为null,但不能

有没有更好的方法来检查response和response.getSubscriber是否存在?

  public Subscriber generateSubscriber(SPRGetSubscriberResponse response) {
        if (response != null) {
            Optional<SPRSubscriber> option = Optional.ofNullable(response.getSubscriber());
            if (option.isPresent()) {
                Subscriber subscriber = new Subscriber();
                //...copy members from response to subscriber

                return subscriber;
            }
        }
        return null;
    }

您正在混合使用条件和Optional ,从而获得所有的笨拙感和流畅性。 仅使用基本功能,没有Optional

if (response != null && response.getSubscriber != null)

在Groovy中:

response?.subscriber // null-safe navigation to collapse your conditional

Java 8的优点:

return Optional.ofNullable(response)
    .map(SPRGetSubscriberResponse::getSubscriber)
    .map(original -> { /* return the copied version */ })
    .orElse(null);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM