How do you simulate a null safe operator with a default return value?

主宰稳场 提交于 2021-02-05 02:29:36

问题


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;

which can be rewritten as

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

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.


回答1:


In Java 8, you could use:

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


来源:https://stackoverflow.com/questions/33403243/how-do-you-simulate-a-null-safe-operator-with-a-default-return-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!