1、GroovyShell类提供一个evaluate方法,可直接运行一段字符串标示的groovy片段
我的业务场景:后台可以手动录入优惠券计算表达式,像下面“quantiry*price*0.8”就是你在后台录入的表达式。
org.codehaus.groovy
groovy-all
2.5.2
pom
public BigDecimal calculatePrice(BigDecimal price, Integer quantity) {
if (price == null || quantity == null) {
return price;
}
BigDecimal result = BigDecimal.ZERO;
try {
Binding binding = new Binding();
binding.setVariable("quantity", quantity);
binding.setVariable("price", price);
GroovyShell groovyShell = new GroovyShell(binding);
result = new BigDecimal(String.valueOf(groovyShell.evaluate("quantity*price*0.8")));
} catch (Exception e) {
return price;
}
return result.compareTo(BigDecimal.ZERO) > 0 ? result : BigDecimal.ZERO;
}
有兴趣 小伙伴可以了解一下groovy