将含有逻辑运算符的字符串解析为逻辑符号

import javax.script.*;
public class TestScript {
    public static void main(String[] args) throws Exception {
        String str = "(a >= 0 && a <= 5)";
          System.out.println(TestScript.isInclude(str,str));
 
    }
      public static Boolean isInclude(String elValue,String elString){ 
      String el = elString.substring(elString.indexOf("(")+1, elString.indexOf(")")); 
      

      System.out.println(el);
      ScriptEngineManager manager = new ScriptEngineManager();  //ScriptEngineManager  和  ScriptEngine   
      ScriptEngine engine = manager.getEngineByName("js");  //ScriptEngine engine = ScriptEngineManager.getEngineByName("js") ;
      engine.put("money",elValue);
      boolean eval = false;
      try {
        eval = (boolean) engine.eval(el);
      } catch (ScriptException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      return eval;
    }

}
 
使用ScriptEngine 对象的eval方法解析逻辑字符串
 
posted on 2018-04-28 14:16  pipizhou  阅读(1282)  评论(0编辑  收藏  举报