Java从数据库中拿出公式进行计算

public static void main(String[] args) {
    // 执行字符串表达式:(k-(x-y)*0.1),进行计算
    Map map = new HashMap();
    map.put("k", 10);
    map.put("x", 2);
    map.put("y", 4);
    String formula = "k-(x-y)*0.1";
    Object result = convertToCode(formula,map);
    System.out.println(result);
}

/**
 * java将字符串转换成可执行代码 工具类
 *
 * @param jexlExp
 * @param map
 * @return
 */
private static Object convertToCode(String jexlExp, Map map) {
    JexlEngine jexl = new JexlEngine();
    Expression expression = jexl.createExpression(jexlExp);
    JexlContext jc = new MapContext();
    for (String key : map.keySet()) {
        jc.set(key, map.get(key));
    }
    if (null == expression.evaluate(jc)) {
        return "";
    }
    return expression.evaluate(jc);
}

要在pom.xml中要添加依赖的jar包


    org.apache.commons
    commons-jexl
    2.1.1

你可能感兴趣的:(java)