Class ExpressionUtil

java.lang.Object
com.sure.tool.util.ExpressionUtil

public class ExpressionUtil extends Object
算术表达式求值工具(零运行期依赖)。

支持文法:+ - * / %、括号、一元负号、整数/小数/科学计数法、变量替换。 实现为 LL(1) 递归下降 + BigDecimal 高精度运算;不支持函数、幂、逻辑比较与字符串。

示例:eval("(1 + 2) * 3 - 4 / 2", map)

Since:
1.9.0
Author:
suretool
  • Method Details

    • eval

      public static double eval(String expression)
      求值无变量算术表达式,返回 double。
      Parameters:
      expression - 表达式
      Returns:
      计算结果
      Throws:
      IllegalArgumentException - 表达式非法或除零
    • eval

      public static double eval(String expression, Map<String,Object> variables)
      求值算术表达式(支持变量替换)。
      Parameters:
      expression - 表达式
      variables - 变量表(值为 Number 或可解析为数字的字符串)
      Returns:
      计算结果
      Throws:
      IllegalArgumentException - 表达式非法、变量缺失或除零
    • evalNumber

      public static BigDecimal evalNumber(String expression, Map<String,Object> variables)
      求值表达式,返回高精度 BigDecimal。
      Parameters:
      expression - 表达式
      variables - 变量表,可为 null
      Returns:
      计算结果
      Throws:
      IllegalArgumentException - 表达式非法、变量缺失或除零
    • check

      public static boolean check(String expression)
      校验表达式是否合法(不含变量求值)。
      Parameters:
      expression - 表达式
      Returns:
      合法返回 true;为 null/空白/文法错误/除零返回 false