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;
}