Reputation: 263
I have the following code using spring expression language:
StandardEvaluationContext stdContext = new StandardEvaluationContext();
stdContext.setVariable("emp", filterInputData);
ExpressionParser parser = new SpelExpressionParser();
parser.parseExpression("#emp.?[name.toLowerCase().contains('Hari')]").getValue(stdContext);
where emp is the name of the bean. Here the name can be null and when calling name.toLowerCase()
I am getting a nullpointer exception. How to handle the null values in this scenario? I need to call toLowercase()
for only non-null values.
Upvotes: 16
Views: 42995
Reputation: 174829
"#emp.name != null ? #emp.name.toLowerCase().contains('hari') : null"
or
"#emp.name != null ? #emp.name.toLowerCase().contains('hari') : false"
depending on what you want back when the name is missing.
Actually, this short form works too...
"#emp.name != null ? toLowerCase().contains('hari') : null"
BTW, in your original question...
name.toLowerCase().contains('Hari')
will never return true (H is upper case).
Or, Elvis is your friend...
Expression expression = new SpelExpressionParser().parseExpression("#emp.name?:'no name found'");
value = expression.getValue(context, String.class).toLowerCase();
Upvotes: 37
Reputation: 2448
Can you Autowire this bean to your class?
Something like:
public class YourClass{
@Autowire
private Employee emp
public boolean func(){
if (emp.getName() != null){
return emp.getName().toLowerCase().contains('Hari');
}else{
return false;
}
}
}
Upvotes: -1