- 表达式
List orders = getOrder(orderID);
foreach(order:orders){
System.out.println('--user:');
System.out.println(order.user.id+' '+order.user.name);
System.out.println('--items:');
double sum=0;
foreach(item:order.items){
p=OrderService.getProduct(item.productID);
itemCost=item.number*p.price;
System.out.println(item.id + '\t'+p.name + '\t' +item.number+'\t' + itemCost);
sum+=itemCost;
}
System.out.println('--total:' +sum);
}
- 代码
String exp = "...";
ParserContext ctx = new ParserContext(); ctx.addImport(List.class);
ctx.addImport(OrderService.class);
ctx.addImport(System.out.getClass());
ctx.addImport("getOrder", OrderService.class.getMethod("getOrder",int.class));
ctx.addImport("getProduct", OrderService.class.getMethod("getProduct",int.class));
ctx.addImport("print", System.out.getClass().getMethod("print",String.class));
Map map = new HashMap();
map.put("orderID", 1);
Serializable serialExp = MVEL.compileExpression(exp, ctx);
MVEL.executeExpression(serialExp, map);