java利用表达式开源项目中的jexl 对 templateId1fieldName product_codefieldOperatorcontainsfieldValueZAKB规则解析生成表达式rootproduct_codecontainsZAKB具体代码怎么实现?以及利用该表达式判断某个对象是否符合条件
- 解析规则生成表达式的代码实现:
import org.apache.commons.jexl3.*;
public class RuleParser {
public static String parse(String rule) {
// 使用 jexl 创建表达式引擎
JexlEngine jexlEngine = new JexlBuilder().create();
// 创建 JEXL 表达式
JexlExpression expression = jexlEngine.createExpression(rule);
// 获取根节点
JexlContext jexlContext = new MapContext();
Object root = expression.evaluate(jexlContext);
// 返回表达式字符串
return expression.toString();
}
public static void main(String[] args) {
String rule = "[{\"templateId\":\"1\",\"fieldName\": \"product_code\",\"fieldOperator\",\"contains\",\"fieldValue\":\"ZAKB\"}]";
String expression = parse("root.product_code.contains(\"ZAKB\")");
System.out.println(expression);
}
}
- 判断某个对象是否符合条件的代码实现:
import org.apache.commons.jexl3.*;
public class RuleEvaluator {
public static boolean evaluate(String expression, Object object) {
// 使用 jexl 创建表达式引擎
JexlEngine jexlEngine = new JexlBuilder().create();
// 创建 JEXL 表达式
JexlExpression jexlExpression = jexlEngine.createExpression(expression);
// 获取根节点
JexlContext jexlContext = new MapContext();
jexlContext.set("root", object);
// 返回表达式结果
Object result = jexlExpression.evaluate(jexlContext);
return result instanceof Boolean && (Boolean) result;
}
public static void main(String[] args) {
String expression = "root.product_code.contains(\"ZAKB\")";
// 假设有一个对象符合条件
Object object = new Object() {
public String getProduct_code() {
return "ZAKB123";
}
};
boolean result = evaluate(expression, object);
System.out.println(result); // true
}
}
需要注意的是,要先将规则解析成表达式,再根据表达式判断对象是否符合条件。同时,要注意对象中的属性名要与表达式中的变量名一致
原文地址: https://www.cveoy.top/t/topic/g7uQ 著作权归作者所有。请勿转载和采集!