mvel探索-1

  1. 表达式
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);
}
 
  1. 代码
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);
 

 今天犯迷糊了

 

//a
ParserContext ctx1 = new ParserContext();			
ctx1.addImport("time", System.class.getMethod("currentTimeMillis"));
Serializable exp1 = MVEL.compileExpression("time()", ctx1);
System.out.println(MVEL.executeExpression(exp1));	
			
//b
ParserContext ctx2 = new ParserContext();
ctx2.addImport("print", System.out.getClass().getMethod(<span style="color: rgb(255, 0, 0);">"print"</span>, String.class));
Serializable exp2 = MVEL.compileExpression("print('test')", ctx2);
System.out.println(MVEL.executeExpression(exp2));

 

     以上两段代码,b段代码始终报错“Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class”。

     开始一直找不到原因,认为是mvel不支持像out这种静态属性的方法,后来分析错误原因才知道自己犯傻了,a段代码不报错是因为currentTimeMillis方法是静态方法,调用时不需要instance,而out下面的print方法不是。


     所以在MVEL中调用System.out.print方法时没法偷懒,只能将b段代码改成:

 

 

ParserContext ctx2 = new ParserContext();
ctx2.addImport("print", System.out.getClass().getMethod("print", String.class));
Serializable exp2 = MVEL.compileExpression(<span style="color: rgb(255, 0, 0);">"System.out.print('test')"</span>, ctx2);
System.out.println(MVEL.executeExpression(exp2));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值