在工程中遇到一个解析开发人员输入的EL表达式是否合法的需求,主要是判断EL表达式中的变量是不是工程中提供的。
本来自己写了一个输入的方法, 但是老板说情况太多,出了问题不好排查,就让我找了开源的JUEL进行解析。
翻看了半天源码,发现只有代码里面构建Tree的代码有用。
正菜:在JUEL中所有非Object型的表达式,都会进入
TreeValueExpression类,在这个类当中将
expression转化为EL的Tree对象,这时候
expression中含有的表达式就绑定在了
identifier中。(在JUEL中称
expression中需要的绑定的类叫做
identifier
)。依赖包只有一个是juel-impl-2.2.7.jar。
有用的代码:
public static void main(String[] args) {
String input = "${test == \"23\"||test2<2}";
TreeBuilder builder = new Builder();
Tree tree =builder.build(input);
Iterable<IdentifierNode> node = tree.getIdentifierNodes();
for(IdentifierNode iden :node){
System.out.println(iden.getName());
}
}