javajexl

Jexl perform dynamic string transformation


I am building an evaluator which underneath uses JEXL. I know how to introduce the workspaces in Jexl, but that only allows a class definition, I need to define a method definition. In the following example, for getting access to log function of Math, I have to add that into the function context. I want to be able to evaluate an expression: "log(5)" i.e. without using the qualifier.

Map<String, Object> funcs = new HashMap<String, Object>();
funcs.put("math", Math.class);

JexlEngine jexl = new JexlBuilder().namespaces(funcs).create();
JexlExpression je = jexl.createExpression("math:log(5)");
je.evaluate();

Solution

  • You can use the 'null' namespace if Math is the sole source of functions.

    Map<String, Object> funcs = new HashMap<String, Object>();
    funcs.put(null, Math.class);
    JexlEngine jexl = new JexlBuilder().namespaces(funcs).create();
    JexlExpression je = jexl.createExpression("log(5)");
    Object result = je.evaluate(null);
    Assert.assertNotNull(result);
    

    If you need more than Math as a source, I'm afraid you'll have to create your own class that delegates each method to its sources.