Not like C or C++, o = objectA.objectB.objectC will throw a NullPointerException if either object(A, B) is null in Java. In Java 1.7, I can't do anything like lambda expression to run this command with try-catch protection.
So, how will you perfectly cache the exception there?
Sadly there is no sort of "propagate null" operator in Java, although it was talked about some while ago. (The notation o = objectA?.objectB?.objectC was mooted).
In your case you need to check each part in turn:
if (objectA == null){
o = null;
} else {
/*OType*/ p = objectA.objectB;
o = p == null ? null : p.objectC;
}
Using purely the ternary conditional operator is also a possibility, but that means you need to write objectA.objectB in more than one place.
Enclosing the expression around a try catch block seems crude to me as it could smother legitimate NullPointerExceptions if the chain comprises functions (although that is a moot point for direct field access). But it is easy to read, and scales better for long chains:
try {
o = objectA.objectB.objectC;
} catch (final java.lang.NullPointerException e){
o = null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With