java利用表达式开源项目中的jexl 对 templateId1fieldName product_codefieldOperatorcontainsfieldValueZAKB规则解析成表达式rootproduct_codecontainsZAKB 具体代码怎么实现?以及利用该表达式判断某个对象是否符合条件
- 使用JEXL解析规则生成表达式:
import org.apache.commons.jexl3.*;
public class RuleParser {
public String parse(String rule) {
String expression = "";
try {
JexlEngine jexl = new JexlBuilder().create();
JexlExpression jexlExp = jexl.createExpression(rule);
expression = jexlExp.toString();
} catch (Exception e) {
System.out.println("解析规则失败:" + e.getMessage());
}
return expression;
}
}
- 判断对象是否符合条件:
import org.apache.commons.jexl3.*;
public class RuleEvaluator {
public boolean evaluate(String expression, Object object) {
try {
JexlEngine jexl = new JexlBuilder().create();
JexlExpression jexlExp = jexl.createExpression(expression);
JexlContext jexlContext = new MapContext();
jexlContext.set("root", object);
Object result = jexlExp.evaluate(jexlContext);
return (Boolean)result;
} catch (Exception e) {
System.out.println("判断对象是否符合条件失败:" + e.getMessage());
return false;
}
}
}
示例代码:
public class Main {
public static void main(String[] args) {
// 解析规则生成表达式
String rule = "root.product_code.contains(\"ZAKB\")";
RuleParser parser = new RuleParser();
String expression = parser.parse(rule);
System.out.println(expression);
// 判断对象是否符合条件
Map<String, String> object = new HashMap<>();
object.put("product_code", "ZAKB123");
RuleEvaluator evaluator = new RuleEvaluator();
boolean result = evaluator.evaluate(expression, object);
System.out.println(result);
}
}
``
原文地址: https://www.cveoy.top/t/topic/g7vv 著作权归作者所有。请勿转载和采集!