Does the MVEL Null-Safe operator work on methods?

2.2k views Asked by At

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")
1

There are 1 answers

0
Mark On BEST ANSWER

As it turns out, the expression

traveler.?getVisitedCountries().contains("France")

does observe the null-safe operator. It would evaluate to null here. Unit test:

@Test
public void testMVELNullSafeOnMethod() throws Exception {
    Traveler traveler = new Traveler();
    // traveler visitedCountries field is null
    String expression = "traveler.?getVisitedCountries().contains(\"France\")";
    Serializable exp = MVEL.compileExpression(expression);
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("traveler", traveler);
    Boolean response = (Boolean) MVEL.executeExpression(exp, map);
    assertNull(response);
}