Unfortunately, you cannot handle this. If you ask me, this is a problem with the Java language. Does Groovy have something called Safe Navigation Operator? that is specifically designed for this purpose. Here are two things I've done in the past.
- The answer that Grisha has already given, so I will not repeat it
Naive code that accesses it and surrounds it in try / catch for NPE. Here is an example:
try { if (foo.bar.boo.far != null) { //do something } } catch (NullPointerException e) { //do what you would do in an else }
I don't like the second option, but I say if it really makes the code cleaner, consider using it.
I once worked with a library, which is a very thin shell on an XML schema, and I decided to use the second option for this case. If I hadn’t done this, the code would have been harder to maintain, because it would have been easy to forget the null check, and they cluttered the important logic. I think this is a valid case for using it.
source share