Results 1 to 2 of 2

Thread: spEL using groovy?

  1. #1

    Default spEL using groovy?

    Hi to all,

    in reading the ref manual in section...

    6.5.10.1 The #this and #root variables

    The variable #this is always defined and refers to the current evaluation object (against which unqualified references are resolved). The variable #root is always defined and refers to the root context object. Although #this may vary as components of an expression are evaluated, #root always refers to the root.

    Code:
    // create an array of integers
    List<Integer> primes = new ArrayList<Integer>();
    primes.addAll(Arrays.asList(2,3,5,7,11,13,17));
    
    // create parser and set variable 'primes' as the array of integers
    ExpressionParser parser = new SpelExpressionParser();
    StandardEvaluationContext context = new StandardEvaluationContext();
    context.setVariable("primes",primes);
    
    // all prime numbers > 10 from the list (using selection ?{...})
    // evaluates to [11, 13, 17]
    List<Integer> primesGreaterThanTen = 
                 (List<Integer>) parser.parseExpression("#primes.?[#this>10]").getValue(context);
    we see #primes.?[#this>10] is this a groovy dot operator ' myArray.?[condition]' ?

    what would it translate to in java code..?
    Code:
    List<Integer> primesGreaterThanTen;
    for (Integer : primes){
      primesGreaterThanTen.add( (this > 10) ? this : null);
    }
    I can't seem to find an example/explanation for ' .? '

    Is there anything to explain this syntax ?

    Thanks

  2. #2

    Default

    in reading further it would appear to be a 'safe navigator' from groovy
    used in case #primes.?[#this>10] had nothing > 10 ..
    am I right?

    6.5.15 Safe Navigation operator

    The Safe Navigation operator is used to avoid a NullPointerException and comes from the Groovy language. Typically when you have a reference to an object you might need to verify that it is not null before accessing methods or properties of the object. To avoid this, the safe navigation operator will simply return null instead of throwing an exception.

    Code:
    ExpressionParser parser = new SpelExpressionParser();
    
    Inventor tesla = new Inventor("Nikola Tesla", "Serbian");
    tesla.setPlaceOfBirth(new PlaceOfBirth("Smiljan"));
    
    StandardEvaluationContext context = new StandardEvaluationContext(tesla);
    
    String city = parser.parseExpression("PlaceOfBirth?.City").getValue(context, String.class);
    System.out.println(city); // Smiljan
    
    tesla.setPlaceOfBirth(null);
    
    city = parser.parseExpression("PlaceOfBirth?.City").getValue(context, String.class);
    
    System.out.println(city); // null - does not throw NullPointerException!!!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •