Java 实现String语句的执行(Jexl)

时间:2023-03-09 03:30:10
Java 实现String语句的执行(Jexl)

https://www.jianshu.com/p/1000719e49fa

1.maven 导入库

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-jexl</artifactId>
<version>2.0</version>
</dependency>

2.代码实例

import org.apache.commons.jexl2.Expression;
import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.JexlEngine;
import org.apache.commons.jexl2.MapContext; import java.util.HashMap;
import java.util.Map; /**
* A Camel Application
*/
public class MainApp { /**
* A main() so we can easily run these routing rules in our IDE
*/
public static Object convertToCode(String jexlExp, Map<String, Object> map) {
//创建或检索引擎
JexlEngine jexl = new JexlEngine();
//创建一个表达式
Expression e = jexl.createExpression(jexlExp);
//创建上下文并添加数据
JexlContext jc = new MapContext();
for (String key : map.keySet()) {
jc.set(key, map.get(key));
}
//现在评估表达式,得到结果
if (null == e.evaluate(jc)) {
return "";
}
return e.evaluate(jc);
} public static void main(String... args) throws Exception {
try {
Map<String, Object> map = new HashMap<String, Object>(16);
map.put("money", 6100);
String expression = "money>=2000&&money<=4000";
Object code = convertToCode(expression, map);
System.out.println((Boolean) code);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

3. 补充:c# Asp.net

using System.Web.Script.Serialization;

 public static object EvalJscript(string str)
{
object Result = null;
str = str.Replace("OR", "||");
str = str.Replace("AND", "&&");
if (ve == null)
{
ve = Microsoft.JScript.Vsa.VsaEngine.CreateEngine();
}
Result = Microsoft.JScript.Eval.JScriptEvaluate(str, ve); return Result;
}

作者:咖啡机an
链接:https://www.jianshu.com/p/1000719e49fa
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。