String表达式的布尔值

/**
 * 
 * @Description (字符串表达式计算逻辑值)
 * @author feizhou
 * @Date 2018年4月13日下午2:30:28  
 * @version 1.0.0
 * @param str
 * @param var
 * @return
 * @throws ScriptException
 */
public static boolean StringtoBoolean(String str, Map<String,Object> var) throws ScriptException {
     ScriptEngineManager manager = new ScriptEngineManager();
     ScriptEngine engine = manager.getEngineByName("js");
     Set<String> keys = var.keySet();
     for (String key : keys) {
         engine.put(key,var.get(key));
    }
     str= str.replaceAll(" or ", " || ").replaceAll(" and ", " && ");
     Object result = engine.eval(str);
    return Boolean.parseBoolean(String.valueOf(result));

}

测试

public static void main(String[] args) throws Exception{

   String str = "outcome=='批准' or outcome=='同意'";
   Map<String,Object> var =new HashMap<String,Object>();
   var.put("outcome", "批准");
   boolean stringtoBoolean = StringtoBoolean(str, var);

   System.out.println("计算结果:" + stringtoBoolean);
   计算结果:true

}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhou920786312/article/details/79966345
个人分类: java其他
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭