jexl表达式解析

1.引入依赖包

<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-jexl -->
    <!--jexl解析表达式-->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-jexl3</artifactId>
      <version>3.1</version>
    </dependency>

2.上代码

public class ExpressionUtil {

    /**
     * @description: 表达式解析并计算并返回BigDecimal类型计算结果
     * @param
     * @return
     * @author GMH
     * @date 2020/7/1 14:12
     */
    public static BigDecimal executeExpressionBigDecimal(String eval, Map<String, Object> map){
        Object object = executeExpression(eval, map);
        return BigDecimal.valueOf(Double.valueOf(Objects.toString(object,"0")));
    }

    /**
     * @description: 根据表达式和参数集合进行计算
     * @param eval "day+1"
     * @param map "key:day,value:31"
     * @return "32"
     * @author GMH
     * @date 2020/7/1 14:08
     */
    private static Object executeExpression(String eval, Map<String, Object> map) {
        JexlExpression expression = new Engine().createExpression(eval);
        JexlContext context = new MapContext();
        if (Objects.nonNull(map)) {
            map.forEach(context::set);
        }
        return expression.evaluate(context);
    }

    public static void main(String[] args) {
        Map<String,Object> map = new HashMap<>();
        map.put("landArea",10100);
        map.put("transactionPrice",10000);
        String eval = "landArea > 1000 ? transactionPrice * 0.5 : transactionPrice * 1";
        BigDecimal res = executeExpressionBigDecimal(eval,map);
        System.out.printf(res.toString());
    }
}

3.测试输出结果

jexl表达式解析_第1张图片

你可能感兴趣的:(java)