I have a question regarding the MVEL null-safe (?
) operator.
Say I have the following Java class:
public class Traveler {
private Set<String> visitedCountries;
public Set<String> getVisitedCountries() {
return visitedCountries;
}
}
If I have an MVEL expression like this:
traveler.visitedCountries.contains("France")
I get a NullPointerException
if the visitedCountries
field is null. To get around this, I can use the null-safe operator:
traveler.?visitedCountries.contains("France")
If visitedCountries
is null, this expression evaluates to null instead of throwing the NPE.
My question is this: does the null-safe operator work on method invocations? For example:
traveler.getVisitedCountries().contains("France")
will throw a NullPointerException
if getVisitedCountries()
returns null.
But what happens if I put in the null-safe operator? What will the following do if the field visitedCountries
is null?
traveler.?getVisitedCountries().contains("France")
As it turns out, the expression
does observe the null-safe operator. It would evaluate to null here. Unit test: