Jexl和Spel表达式解析对内部类的支持

项目中用到了把字符串解析成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

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值