• 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
    來源:简书
    简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
  • 相关阅读:
    Java入门3.2---线程池
    Java入门3.1---多线程
    打开ppt报"powerpoint无法加载mathtype加载项"错误
    LATEX排版总结
    casbin 权限系统
    Go netpoll I/O 多路复用构建原生网络模型之源码深度解析
    使用winsw包装服务将nginx包装为Windows服务
    Node.js 的模块系统
    一文读懂 babel7 的配置文件加载逻辑
    vue-cli是什么?和 webpack是什么关系?
  • 原文地址:https://www.cnblogs.com/kakaisgood/p/10382309.html
Copyright © 2020-2023  润新知