Java-Apache Commons Jexl3-动态表达式判断
转自:https://www.cnblogs.com/yqk150/p/14367542.html
pom.xml引入maven坐标
<!-- 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 语句块。标签:灾害,gradeName,grade,jexl3,jexlContext,引擎,Jexl,表达式 From: https://www.cnblogs.com/chyf1990/p/16913280.html
正确: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='无灾害';}}");