1. 程式人生 > >Java 實現String語句的執行(Jexl)

Java 實現String語句的執行(Jexl)

咖啡 -c literal apache money ram class title auto

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
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並註明出處。

Java 實現String語句的執行(Jexl)