项目中用到了把字符串解析成java表达式的功能,一开始用的Apache的Jexl,但是Jexl不支持对内部类方法调用的解析,经过尝试发现Spel可以。现对这两者进行一个总结。
假设有如下类
public class Out {
private String name = "zzj";
class In {
public void helloIn() {
System.out.println("i am helloIn");
System.out.println(Out.this.name);
}
}
}
现有一个字符串如下,需要把字符串解析为对内部类In的helloIn方法的调用
"in.helloIn()"
//解析字符串以达到如下调用效果
Out out = new Out();
Out.In in = out.new In();
in.helloIn();
用Jexl解析
Out out = new Out();
Out.In in = out.new In();
JexlEngine jexl = new JexlBuilder().create();
JexlExpression expression = jexl.createExpression("in.helloIn()");
JexlContext context = new MapContext();
context.set("in", in);
Object value = expression.evaluate(context);
System.out.println(value);
//解析不成功,报如下错误
Exception in thread "main" org.apache.commons.jexl3.JexlException$Method: com.zzj.springboot.outin.Main.main@1:3 unsolvable function/method 'helloIn'
at com.zzj.springboot.outin.Main.main(Main.java:17)
用Spel解析
ExpressionParser parser = new SpelExpressionParser();
EvaluationContext ctx = new StandardEvaluationContext();
ctx.setVariable("in", in);
Object value = parser.parseExpression("#in.helloIn()").getValue(ctx);
System.out.println(value);
//解析成功,打印如下结果
i am helloIn
zzj
null //因为返回值是void,所以value是null