如何模拟具有默认返回值的null安全运算符? [英] How do you simulate a null safe operator with a default return value?

查看:69
本文介绍了如何模拟具有默认返回值的null安全运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,标题不可用,但是我找不到用一个句子来描述问题的好方法.简而言之,按照这种模式,我有很多Java代码

I'm sorry for the title but I cant find a good way to describe the problem in one sentence. In short, I have a lot of Java code following this pattern

if (obj != null && obj.getPropertyX() != null) {
    return obj.getPropertyX();
}
return defaultProperty;

可以改写为

return obj != null && obj.getPropertyX() != null ? obj.getPropertyX() : defaultProperty;

它仍然很丑陋,我想知道Google Guava或其他库中是否有一些API可以帮助清理此代码.具体来说,我正在寻找类似的东西

It's still ugly and I'm wondering if there is some API in Google Guava or other library to help clean up this code. Specifically, I'm looking for something like

return someAPI(obj, "getPropertyX", defaultProperty);

我可以使用反射来实现此方法,但是我不确定这是否是正确的方法.谢谢.

I can implement this method using reflection but I'm not sure if that's the proper way to do it. Thanks.

推荐答案

在Java 8中,您可以使用:

In Java 8, you could use:

return Optional.ofNullable(obj).map(Obj::getPropertyX).orElse(defaultProperty);

这篇关于如何模拟具有默认返回值的null安全运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆