Mvel动态表达

时间:2015-05-12 17:39:48

标签: mvel

您知道是否可以使用Mvel动态评估表达式。例如:

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);

1 个答案:

答案 0 :(得分:0)

几乎没有做出任何改变

1。)Brace在最后添加,在return result;之前关闭。

2。)int result=0,声明已添加。

3。)if(op1 == 'true'),它不是boolean,而是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);

<强>输出

30
相关问题