今天用MVEL犯迷糊了

 

 

//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("print", 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("System.out.print('test')", ctx2);
System.out.println(MVEL.executeExpression(exp2));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值