使用示例如下
package com.zyy.tyy.zyytyy.test;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import com.googlecode.aviator.runtime.type.AviatorFunction;
import java.util.HashMap;
import java.util.Map;
public class TestAviator {
public static void main(String[] args) {
String expression1 = "8.29 <= 8.29 && 9.388 >= 9.388";
System.out.println(expression1 + " = " + AviatorEvaluator.execute(expression1));
Map<String, Object> env = new HashMap<>();
env.put("name", "zyy");
System.out.println(AviatorEvaluator.execute("'my name is: ' + name", env));
String myName = "zyy";
System.out.println(AviatorEvaluator.exec("'exec my name is: ' + name", myName));
String function = "string.length('hello')";
System.out.println(function + " = " + AviatorEvaluator.execute(function));
AviatorEvaluator.addFunction(new TestAviatorAddFunction());
System.out.println("self function: " + AviatorEvaluator.execute("add(614, 1001)"));
AviatorEvaluator.removeFunction("add");
String expression2 = "a - (b - c) > 3";
Expression exp = AviatorEvaluator.compile(expression2);
Map<String, Object> env2 = new HashMap<>();
env2.put("a", 6.14);
env2.put("b", 10.01);
env2.put("c", 6.14);
boolean execute = (boolean) exp.execute(env2);
System.out.println(execute);
}
}
自定义函数
package com.zyy.tyy.zyytyy.test;
import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorDouble;
import com.googlecode.aviator.runtime.type.AviatorObject;
import java.util.Map;
public class TestAviatorAddFunction extends AbstractFunction {
@Override
public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2) {
Number left = FunctionUtils.getNumberValue(arg1, env);
Number right = FunctionUtils.getNumberValue(arg2, env);
return new AviatorDouble(left.doubleValue() + right.doubleValue());
}
@Override
public String getName() {
return "add";
}
}