一样可以支持mvel类似的表达式计算,偏简单
package com.example.demo.mymvel;import java.util.Map;import java.util.regex.Pattern;import java.util.regex.Matcher;import javax.script.ScriptEngine;import javax.script.ScriptEngineManager;/*** 描述:Mvel表达式执行器 </br>* 作者:IT学习道场 </br>* 时间:2023/5/6 17:20*/public class MvelExpressionEvaluator {/*** 表达式*/private String expression;public MvelExpressionEvaluator(String expression) {this.expression = expression;}/*** 执行表达式执行* @param variables 表达式入参参数* @return object - 表达式返回的值* @throws Exception*/public Object evaluate(Map variables) throws Exception {String parsedExpression = parseExpressionWithVariables(expression, variables);//加载js脚本引擎ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");return engine.eval(parsedExpression);}/*** 解析参数表达式* @param expression 原表达式* @param variables 参数map* @return*/private String parseExpressionWithVariables(String expression, Map variables) {Pattern pattern = Pattern.compile("\\{(.+?)\\}");Matcher matcher = pattern.matcher(expression);StringBuffer sb = new StringBuffer();while (matcher.find()) {String variableName = matcher.group(1).trim();if (variables.containsKey(variableName)) {Object variableValue = variables.get(variableName);matcher.appendReplacement(sb, variableValue.toString());}}matcher.appendTail(sb);return sb.toString();}}
测试
package com.example.demo.mymvel;import java.util.HashMap;import java.util.Map;/*** 描述:测试 </br>* 作者:IT学习道场 </br>* 时间:2023/5/6 17:20*/public class Test {public static void main(String[] args) {Map variables = new HashMap<>();variables.put("x", 1);variables.put("y", 2);variables.put("z", 3);//String rule = "({x} + {y}) * {z}";String rule = "{x} > 1 && {y} > 1";MvelExpressionEvaluator evaluator = new MvelExpressionEvaluator(rule);try {Object result = evaluator.evaluate(variables);System.out.println(result);} catch (Exception e) {e.printStackTrace();}}}
文章转载自IT学习道场,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




