tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 
 Spring > Expression Language > Safe Navigation Operator

Safe Navigation Operator 

The Spring Expression Language (SpEL) is a simple and powerful expression language which helps to query and manipulate objects at runtime. Often while traversing object graphs its required to check whether a particular property is non null and then dig further. The SpEL Safe Navigation Operator (?.) is very useful to navigate object graphs.

File Name  :  
com/bethecoder/tutorials/spring3/tests/spel/SafeNavigationOperatorTest.java 
Author  :  Sudhakar KV
Email  :  kvenkatasudhakar@gmail.com
   
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;

import com.bethecoder.tutorials.spring3.basic.Employee;

public class SafeNavigationOperatorTest {

  /**
   @param args
   */
  public static void main(String[] args) {

    StandardEvaluationContext stdContext = new StandardEvaluationContext();
    Employee employee = new Employee(1"BTC"9999);
    stdContext.setVariable("emp", employee);
    
    ExpressionParser parser = new SpelExpressionParser();
    String value = parser.parseExpression(
        "#emp?.name").getValue(stdContext, String.class);
    System.out.println(value);   //BTC

    stdContext.setVariable("emp"null);
    value = parser.parseExpression("#emp?.name").getValue(stdContext, String.class);
    System.out.println(value);    //null

    
    stdContext.setVariable("emp", employee);
    value = parser.parseExpression(
        "#emp?.name?.toLowerCase()").getValue(stdContext, String.class);
    System.out.println(value);    //btc
    
    
    stdContext.setVariable("emp"null);
    value = parser.parseExpression(
        "#emp?.name?.toLowerCase()").getValue(stdContext, String.class);
    System.out.println(value);    //null
    
  }

}
   

It gives the following output,
BTC
null
btc
null


                    Print

   



Books Recommendation

 
 
bl  br