工具类
import java.math.BigDecimal;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;
import org.mvel2.CompileException;
import org.mvel2.MVEL;
import org.mvel2.PropertyAccessException;
/**
* 计算工具
*
* @author valsong
* @date Jul 24, 2017
*
*/
public class CalculateUtils {
/**
* 根据传入的公式和参数进行计算
*
* @param formula
* @param variables
* @return
*/
public static <T> BigDecimal calculate(String formula, Map<String, T> variables) {
if (SimpleStringUtils.isBlank(formula)) {
throw new CalculateException("MVEL formula can't be null! formula : " + formula); // 公式不能为空
}
if (variables == null || variables.size() == 0) {
throw new CalculateException("MVEL variables can't be null! variables : " + String.valueOf(variables)); // 参数不能为空
}
try {
// 将公式中的变量全部转化为BigDecimal类型
variables.entrySet().stream().filter(e -> e != null && e.getKey() != null && e.getValue() != null)
.map(CalculateUtils::convert).collect(Collectors.toMap(Entry::getKey, Entry::getValue));
} catch (NumberFormatException e) {
throw new CalculateException(
"MVEL can't convert to BigDecimal, please check the variables : " + String.valueOf(variables) + "!",
e);
} catch (Exception e) {
throw e;
}
BigDecimal result = null;
try {
result = (BigDecimal) MVEL.eval(formula, variables);
} catch (PropertyAccessException pae) {
throw new CalculateException(
"MVEL please check the formula :" + formula + " & variables : " + String.valueOf(variables) + "!",
pae);
} catch (CompileException ce) {
throw new CalculateException("MVEL calculate error! ", ce);
} catch (Exception e) {
throw e;
}
return result;
}
/**
* 将参数转化为Bigdecimal类型
*
* @param entry
* @return
*/
@SuppressWarnings("unchecked")
public static <T> Entry<String, T> convert(Entry<String, T> entry) {
if (entry != null) {
BigDecimal value = null;
if (entry.getValue() instanceof BigDecimal) {
value = (BigDecimal) entry.getValue();
} else {
value = NumberUtils.getNum(NumberUtils.getNum(entry.getValue()));
}
entry.setValue((T) value);
}
return entry;
}
}
异常类
/**
* 计算异常
*
* @author Val Song
* @date Jul 28, 2017
*
*/
public class CalculateException extends RuntimeException {
private static final long serialVersionUID = 5162710183389028792L;
/**
* Constructs a {@code CalculateException} with no detail message.
*/
public CalculateException() {
super();
}
/**
* Constructs a {@code CalculateException} with the specified detail
* message.
*
* @param message
* the detail message.
*/
public CalculateException(String message) {
super(message);
}
/**
* Constructs a {@code CalculateException} with the specified detail
* message & cause
*
* @param message
* @param cause
*/
public CalculateException(String message, Throwable cause) {
super(message, cause);
}
}
字符串工具类
/**
* 字符串工具
*
* @author valsong
*
*/
public class SimpleStringUtils {
/**
* 判断字符串不为空
*
* @param str
* @return
*/
public static boolean isNotBlank(String str) {
return !isBlank(str);
}
/**
* 判断字符串为空
*
* @param str
* @return
*/
public static boolean isBlank(String str) {
if (str == null || "".equals(str.trim())) {
return true;
}
return false;
}
/**
* 去首尾空格
*
* @param s
* @return
*/
public static <T> String trim(T s) {
if (s instanceof String) {
return s == null ? null : ((String) s).trim();
} else {
return s == null ? null : String.valueOf(s).trim();
}
}
/**
* 下划线命名转驼峰式
*
* @param str
* @return
*/
public static String toCamel(String str) {
if (SimpleStringUtils.isBlank(str)) {
return str;
}
StringBuffer buffer = new StringBuffer();
str = str.toLowerCase().trim();
char[] charArray = str.toCharArray();
if (charArray != null) {
for (int i = 0; i < charArray.length; i++) {
if ('_' == charArray[i]) {
i = i + 1;
buffer.append(Character.toUpperCase(charArray[i]));
} else {
buffer.append(charArray[i]);
}
}
}
return buffer.toString();
}
/**
* 驼峰转下划线
*
* @param str
* @return
*/
public static String toUnderline(String str) {
if (SimpleStringUtils.isBlank(str)) {
return str;
}
StringBuffer buffer = new StringBuffer();
str = str.trim();
char[] charArray = str.toCharArray();
if (charArray != null) {
for (int i = 0; i < charArray.length; i++) {
if (Character.isUpperCase(charArray[i])) {
buffer.append("_");
buffer.append(Character.toLowerCase(charArray[i]));
} else {
buffer.append(charArray[i]);
}
}
}
return buffer.toString();
}
}
测试类简单粗暴String Double Integer Bigdecimal 都能支持
public class CalculateUtilsTest {
/**
* 20 * 100 - ( 30 -20 ) + 20 ^ 3 + 20/2
*/
@Test
public void calculateTest4() {
String formula = "A * B - (C -D) + E.pow(F) + G / H";
Map<String, Object> variables = new HashMap<>();
variables.put("A", "20");
variables.put("B", 100L);
variables.put("C", 30.0D);
variables.put("D", 20);
variables.put("E", new BigDecimal("20"));
variables.put("F", "3");
variables.put("G", "20");
variables.put("H", "2");
BigDecimal result = CalculateUtils.calculate(formula, variables);
Assert.assertTrue(new BigDecimal("10000.0").compareTo(result) == 0);
}
}