Aviator是一个轻量级、高性能的Java表达式执行引擎,它动态地将表达式编译成字节码并运行。可被用于动态的公式计算、规则执行和过滤等场景
<dependency>
<groupId>com.googlecode.aviatorgroupId>
<artifactId>aviatorartifactId>
<version>4.2.0version>
dependency>
public class AnswerApp {
public static void main(String[] args) throws Exception {
// 表达式
String express = "x*x+y*y";
Expression expression = AviatorEvaluator.compile(express);
// 表达式中 x的值设置为 10, y的值设置为5
Map<String, Object> params = ImmutableMap.of("x", 10, "y", 5);
Object result = expression.execute(params);
System.out.println("result: "+ result);
}
}
程序运行结果
result: 125
public class AnswerApp {
public static void main(String[] args) throws Exception {
Long result = (Long) AviatorEvaluator.execute("10 * 10 + 5 * 5");
System.out.println("result: " + result);
System.out.println();
String name = "Answer.AI.L";
String language = "Java";
Map<String, Object> map = ImmutableMap.of("myProp1", name, "myProp2", language);
Object result1 = AviatorEvaluator.execute("'Hello ' + myProp1 + ', Hello ' + myProp2", map);
System.out.println("result1: " + result1);
}
}
程序运行结果
result: 125
result1: Hello Answer.AI.L, Hello Java
public class AnswerApp {
public static void main(String[] args) throws Exception {
// ns
System.out.println(AviatorEvaluator.execute("string.substring('AnswerAIL',1,3)"));
// true
System.out.println(AviatorEvaluator.execute("string.contains(\"AnswerAIL\",\"AI\")"));
// true
System.out.println(AviatorEvaluator.execute("string.contains(\"Answer\",string.substring('AnswerAIL',1,3))"));
// 求n次方
AviatorEvaluator.execute("math.pow(-3,2)");
// 开平方根
AviatorEvaluator.execute("math.sqrt(14.0)");
// 正弦函数
AviatorEvaluator.execute("math.sin(20)");
}
}
public class MySumFunction extends AbstractFunction {
@Override
public AviatorObject call(Map<String, Object> env, AviatorObject a, AviatorObject b, AviatorObject c) {
Number numA = FunctionUtils.getNumberValue(a, env);
Number numB = FunctionUtils.getNumberValue(b, env);
Number numC = FunctionUtils.getNumberValue(c, env);
long result = numA.longValue() + numB.longValue() + numC.longValue();
// return new AviatorDouble(numA.longValue() + numB.longValue() + numC.longValue());
return AviatorLong.valueOf(result);
}
/**
* 获取函数名
* */
@Override
public String getName() {
return "mySum";
}
}
public class AnswerApp {
public static void main(String[] args) throws Exception {
// 注册函数
AviatorEvaluator.addFunction(new MySumFunction());
String expression = "mySum(x, y, z)";
Map<String, Object> params = ImmutableMap.of("x", 1, "y", 2, "z", 3);
long result = (long) AviatorEvaluator.execute(expression, params);
System.out.printf("result : " + result);
}
}
程序运行结果
result : 6