Java-Apache Commons Jexl3-动态表达式判断
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-jexl3 --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-jexl3</artifactId> <version>3.1</version> </dependency>
/** * Jexl表达式计算 */ @Test public void jexlUseFun() { // 初始化Jexl构造器 JexlBuilder jexlBuilder = new JexlBuilder(); // 创建Jexl表达式引擎 JexlEngine jexlEngine = jexlBuilder.create(); // 创建Jexl表达式解析器 JexlScript jexlScript = jexlEngine.createScript("if(tem>=25){grade=1;gradeName='有灾害';}else{grade=0;gradeName='无灾害';}"); // 创建Jexl表达式变量上下文 JexlContext jexlContext = new MapContext(); jexlContext.set("tem", 15); // 执行Jexl表达式,得到结果 jexlScript.execute(jexlContext); System.out.println(jexlContext.get("grade")); System.out.println(jexlContext.get("gradeName")); }
注意:Jexl引擎能够创建两种解析器,其中JexlExpression不能使用 if、for、while 语句块。
正确:JexlScript jexlScript = jexlEngine.createScript("if(tem>=25){grade=1;gradeName='有灾害';}else{grade=0;gradeName='无灾害';}");
错误:JexlExpression jexlExpression = jexlEngine.createExpression("{if(tem>=25){grade=1;gradeName='有灾害';}else{grade=0;gradeName='无灾害';}}");