java 实现根据计算公式得出计算结果
1.引入依赖包
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-jexl</artifactId>
<version>2.1.1</version>
</dependency>
2.测试
public static void main(String[] args){
// 执行字符串表达式:(k-(x-y)*0.1),进行计算
Map<String, Object> map = new HashMap<String, Object>();
map.put("k", 10.333);
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将字符串转换成可执行代码 工具类
*
*@paramjexlExp
*@parammap
*@return
*/
private static Object convertToCode(String jexlExp, Map<String, Object> 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);
}
网友评论