In this post under Spring SpEl, I will explain with example the usage of safe navigation operator.
Lets say we have below pojo class
Employee
package spel.package24;
public class Employee {
private Integer id;
private String name;
private int salary;
public Employee() {
}
public Employee(Integer id, String name, int salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
//Removed getter and setter for brevity
}
And if we have the below SpEL expression
name.length
If “name” is null. We get an exception.
To avoid that exception we use the safe navigation operator “?”. After using this operator instead of getting an exception, the expression will return “null”.
We modify the above SpEL expression using safe navigation operator as shown below
name?.length
Below is the main class showing the usage
Main class
package spel.package23;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.SpelEvaluationException;
import org.springframework.expression.spel.standard.SpelExpression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
public class Example23 {
public static void main(String[] args) {
Employee employee = new Employee(1, null, 1000);
SpelExpressionParser spelExpressionParser = new SpelExpressionParser();
try {
Expression expression = spelExpressionParser.parseExpression("name.length");
Integer result = expression.getValue(employee, Integer.class);
System.out.println("Result of 'name.length'-->" + result);
} catch(SpelEvaluationException spelEvaluationException) {
System.out.println(spelEvaluationException.getMessage());
}
Expression expression = spelExpressionParser.parseExpression("name?.length");
Integer result = expression.getValue(employee, Integer.class);
System.out.println("Result of 'name?.length'-->" + result);
}
}
In the above code, at line 14, we create an “Expression” instance for SpEL expression “name.length”.
At line 15, we evaluate the expression and get an exception which is printed to console at line 18.
At line 21, I create another instance of “Expression” instance for SpEL expression “name?.length”. Note the use of safe navigation operator.
At line 22, we evaluate the expression and get “null” as return value which is printed to console at line 23.
In this way we can use safe navigation operator in SpEL
Below is the output
Output
Result of 'name.length'-->EL1007E: Property or field 'length' cannot be found on null
Result of 'name?.length'-->null