同一类型,每条数据,执行不同逻辑
一、例子
设备表:
public class Equipment {private Long id;private Boolean state;//开关private String logic;//判断开关所要执行的逻辑
}
设备数据:
[{"id": 1,"state": true,"logic": "equipValue == 1"},{"id": 2,"state": false,"logic": "equipValue == 0"},{"id": 3,"state": true,"logic": "equipValue == 1 && humidity < 80"}
]
解决方法:
public class MainApp {public static void main(String[] args) {// 初始化 JEXL 引擎JexlEngine jexl = new JexlBuilder().create();// 创建设备对象Equipment equip1 = new Equipment(1L, true, "equipValue == 1 && temperature < 50");Equipment equip2 = new Equipment(2L, false, "equipValue == 0 && pressure > 10");Equipment equip3 = new Equipment(3L, true, "equipValue == 1 && humidity < 80");// 模拟变量输入Map<String, Object> variables1 = new HashMap<>();variables1.put("equipValue", 1);variables1.put("temperature", 45);Map<String, Object> variables2 = new HashMap<>();variables2.put("equipValue", 0);variables2.put("pressure", 15);Map<String, Object> variables3 = new HashMap<>();variables3.put("equipValue", 1);variables3.put("humidity", 75);// 判断设备状态System.out.println("Equip1 should be on? " + evaluateState(jexl, equip1, variables1));System.out.println("Equip2 should be on? " + evaluateState(jexl, equip2, variables2));System.out.println("Equip3 should be on? " + evaluateState(jexl, equip3, variables3));}/*** 使用 JEXL 表达式计算设备是否应为开启状态*/public static boolean evaluateState(JexlEngine jexl, Equipment equipment, Map<String, Object> variables) {try {// 构建上下文JexlContext context = new MapContext(variables);// 解析并执行表达式JexlExpression expression = jexl.createExpression(equipment.getLogic());Object result = expression.evaluate(context);// 返回布尔结果return Boolean.TRUE.equals(result);} catch (Exception e) {System.err.println("Error evaluating expression for equipment: " + equipment.getId() + " - " + e.getMessage());// 出错时返回原始 statereturn equipment.isState();}}
}
二、所用依赖
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-jexl3</artifactId><version>3.5</version> <!-- 可根据需求替换为最新版本 -->
</dependency>implementation 'org.apache.commons:commons-jexl3:3.5' // 可根据需求替换为最新版本
用法:
import org.apache.commons.jexl3.*;public class JexlExample {public static void main(String[] args) {JexlEngine engine = new JexlBuilder().create();String expression = "vars.temperature > 30 ? 'high' : 'normal'";JexlExpression jexlExpr = engine.createExpression(expression);JexlContext context = new MapContext();((MapContext) context).set("temperature", 35);Object result = jexlExpr.evaluate(context);System.out.println(result); // 输出: high}
}