Java – how to simulate a null safe operator with a default return value?
•
Java
I'm sorry for the title, but I can't find a good way to describe the problem in one sentence In short, I have a lot of Java code that follows this pattern
if (obj != null && obj.getPropertyX() != null) { return obj.getPropertyX(); } return defaultProperty;
Can be rewritten as
return obj != null && obj.getPropertyX() != null ? obj.getPropertyX() : defaultProperty;
It's still ugly. I wonder if there are any APIs in Google guava or other libraries to help clean up this code Specifically, I'm looking for something similar
return someAPI(obj,"getPropertyX",defaultProperty);
I can use reflection to implement this method, but I'm not sure if it's the right method thank you.
Solution
In Java 8, you can use:
return Optional.ofNullable(obj).map(Obj::getPropertyX).orElse(defaultProperty);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码