问题
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