Mvel 动态表达式
Mvel dynamic expression
您知道是否可以使用 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.) 最后添加大括号,在 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
您知道是否可以使用 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.) 最后添加大括号,在 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