Elvis Operator
The Spring Expression Language (SpEL ) is a simple and powerful expression language
which helps to query and manipulate objects at runtime.
The following example shows using Elvis operator. It behaves similar to Ternary operator.
Its shorter syntax is handy while evaluating complex expressions.
package com.bethecoder.tutorials.spring3.tests.spel;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
public class ElvisOperatorTest {
/**
* @param args
*/
public static void main ( String [] args ) {
ExpressionParser parser = new SpelExpressionParser () ;
StandardEvaluationContext stdContext = new StandardEvaluationContext () ;
String value = null ;
stdContext.setVariable ( "user" , "BTC" ) ;
value = parser.parseExpression (
"#user?: 'Unknown User'" ) .getValue ( stdContext, String. class ) ;
System.out.println ( value ) ; //BTC
stdContext.setVariable ( "user" , null ) ;
value = parser.parseExpression (
"#user?: 'Unknown User'" ) .getValue ( stdContext, String. class ) ;
System.out.println ( value ) ; //Unknown User
}
}
It gives the following output,
BTC
Unknown User