Search code examples
evalxtend

Xtend: evaluate expression directly from a string


Is there a possibilty in the Xtend language to evaluate an expression directly from a string, e.g. like Eval in Groovy. I want to do something like this in Xtend (the example is from Groovy):

import groovy.util.Eval

assert Eval.me('2*5') == 10

If there is no built-in way to do this, what would be the most similar alternative to achieve this (if any)?

P.S. Just to be clear: the expression is of course not just a simple math operation (like in the example); in particular, I would like to call my own Xtend function doing some transformation on a list.


Solution

  • I think there isn't anything like this in Xtend, so you should probably look for Java libraries that do this.

    For example Java EL seems like a good standard way for evaluating strings. Since EL 3 there is the ELProcessor which doesn't require JSP anymore and it seems quite easy to use:

    ELProcessor elp = new ELProcessor();
    elp.defineBean("employee", new Employee("Charlie Brown"));
    String name = elp.eval("employee.name");
    

    Here is nice article about the latest features of EL, like lambda expression. The article also contains some examples about collections and how to call external methods.