Search code examples
mvel

Mvel dynamic expression


Do you know if it's possible to dynamically evaluate an expression with Mvel. For example :

VariableResolverFactory functionFactory = new MapVariableResolverFactory();
MVEL.eval("def SUM(op1,op2,op3) { result=0B; if(op1) result+=op2; else result+=op3; }  return result; ",functionFactory);

ParserContext ctx = new ParserContext()
Serializable s = MVEL.compileExpression("SUM(op1,op2,op3)", ctx);
contextMapFct.put("op1", "5 > 3"); // just as an example if it's useless
contextMapFct.put("op2", new BigDecimal(10));
contextMapFct.put("op3", new BigDecimal(30));
Object obj= MVEL.executeExpression(s, contextMapFct, this.functionFactory);

Solution

  • Few changes done

    1.) Brace added at the last, was closing before return result;.

    2.) int result=0, declaration added.

    3.) if(op1 == 'true'), it is not coming as boolean, but as String

    VariableResolverFactory functionFactory = new MapVariableResolverFactory();
    MVEL.eval(
            "def SUM(op1,op2,op3) { int result=0; if(op1 == 'true') result+=op2; else result+=op3;   return result; }",
            functionFactory);
    
    ParserContext ctx = new ParserContext();
    Serializable s = MVEL.compileExpression("SUM(op1,op2,op3)", ctx);
    Map contextMapFct = new HashMap();
    contextMapFct.put("op1", "5 > 3"); // just as an example if it's useless
    contextMapFct.put("op2", new BigDecimal(10));
    contextMapFct.put("op3", new BigDecimal(30));
    Object obj = MVEL.executeExpression(s, contextMapFct, functionFactory);
    System.out.println(obj);
    

    output

    30