Is there an elegant way to check if a string of fields is null?
Let's say I have:
String fieldD = myString.getFieldA().getFieldB().getFieldC().getFieldD();
I could do something like
String fieldD = null;
if (myString.getFieldA() != null
&& myString.getFieldA().getFieldB() != null
&& myString.getFieldA().getFieldB().getFieldC() != null) {
String fieldD = myString.getFieldA().getFieldB().getFieldC().getFieldD();
}
or I could do something like
String fieldD = null;
try {
String fieldD = myString.getFieldA().getFieldB().getFieldC().getFieldD();
} catch (NullPointerException e) {
// do nothing
}
But there has to be a more elegant solution than either of these right? I'm sure this is already answered somewhere, but I can't seem to find it.