利用Jexl实现数据库的计算公式在Java中执行
Posted yiosi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了利用Jexl实现数据库的计算公式在Java中执行相关的知识,希望对你有一定的参考价值。
public class JexlEngineUtils {
public static BigDecimal evaluateExpression (
Map <String, Object> map, String[] elementArr, String expression, int margin
){
JexlEngine jexl = new JexlEngine ();
JexlContext jexlContext = new MapContext ();
//需要set源代码Math,否则报错
jexlContext.set("Math", Math.class);
//需要set源代码 BigDecimal,否则报错
jexlContext.set("BigDecimal",BigDecimal.class);
for (String key : elementArr) {
Object p = map.get ( key );
Double val = 0.0;
if (null != p) {
if (p instanceof BigDecimal) {
BigDecimal temp = (BigDecimal) p;
val = temp.doubleValue ();
} else {
if (RegexUtils.isNumberWithDot ( p.toString () )) {
val = Double.valueOf ( p.toString () );
}
}
}
jexlContext.set ( key, val );
}
Expression e = jexl.createExpression ( expression );
Object obj = e.evaluate ( jexlContext );
BigDecimal result = new BigDecimal ( null == obj ? "0" : obj.toString () );
return result.setScale ( margin, BigDecimal.ROUND_HALF_UP );
}
//因为精度问题引入BigDecimal
public static void main(String[] args) {
Map<String, Object> individualIncomeTaxMap = new HashMap<>(16);
individualIncomeTaxMap.put("cashRate",5334.4);
individualIncomeTaxMap.put("yearPremium",200000);
String[] te = {"cashRate","yearPremium"};
System.out.println(evaluateExpression(individualIncomeTaxMap,te,"Math.floor(BigDecimal.valueOf(cashRate).multiply(BigDecimal.valueOf(yearPremium).divide(BigDecimal.valueOf(1000))))",0));
}
}
以上是关于利用Jexl实现数据库的计算公式在Java中执行的主要内容,如果未能解决你的问题,请参考以下文章