今天用MVEL犯迷糊了
?
?
//aParserContext ctx1 = new ParserContext();ctx1.addImport("time", System.class.getMethod("currentTimeMillis"));Serializable exp1 = MVEL.compileExpression("time()", ctx1);System.out.println(MVEL.executeExpression(exp1));//bParserContext 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));1 楼 omeweb 2011-10-18 System.out.print可以直接调用,in mvel2