1. 程式人生 > >利用Jexl實現數據庫的計算公式在Java中執行

利用Jexl實現數據庫的計算公式在Java中執行

bject urn arp key cal object num regex ply

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中執行