Aviator是一个轻量级、高性能的Java表达式执行引擎, 本文内容主要来自于官方文档
简介
=~?:
包依赖
commons-beanutils
<dependency>
<groupId>com.googlecode.aviator</groupId>
<artifactId>aviator</artifactId>
<version>2.3.3</version>
</dependency>
- 1
- 2
- 3
- 4
- 5
使用手册
执行表达式
com.googlecode.aviator.AviatorEvaluator1+2+3
import com.googlecode.aviator.AviatorEvaluator;
public class TestAviator {
public static void main(String[] args) {
Long result = (Long) AviatorEvaluator.execute("1+2+3");
System.out.println(result);
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
LongIntegerAviatorLongDoubleLongDouble6
使用变量
say hello
public class TestAviator {
public static void main(String[] args) {
String yourName = "Michael";
Map<String, Object> env = new HashMap<String, Object>();
env.put("yourName", yourName);
String result = (String) AviatorEvaluator.execute(" 'hello ' + yourName ", env);
System.out.println(result); // hello Michael
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
yourNamenullMapyourNameenvkeyvalue'hello 'AviatorStringAviatorStringStringunicodeStringStringString\n、\\、\'
AviatorEvaluator.execute(" 'a\"b' "); // 字符串 a"b
AviatorEvaluator.execute(" \"a\'b\" "); // 字符串 a'b
AviatorEvaluator.execute(" 'hello ' + 3 "); // 字符串 hello 3
AviatorEvaluator.execute(" 'hello '+ unknow "); // 字符串 hello null
- 1
- 2
- 3
- 4
exec 方法
execenvmap
String name = "dennis";
AviatorEvaluator.exec(" 'hello ' + yourName ", name); // hello dennis
- 1
- 2
execMap
调用函数
Aviator 支持函数调用, 函数调用的风格类似 lua, 下面的例子获取字符串的长度:
AviatorEvaluator.execute("string.length('hello')"); // 5
- 1
string.length('hello')string.length'hello'string.substring
AviatorEvaluator.execute("string.contains(\"test\", string.substring('hello', 1, 2))"); // true
- 1
string.substring('hello', 1, 2)'e'string.containse'test'
自定义函数
com.googlecode.aviator.runtime.type.AviatorFunctionAviatorEvaluatorAviatorFunctionAbstractFunctionoverride
add
public class TestAviator {
public static void main(String[] args) {
//注册函数
AviatorEvaluator.addFunction(new AddFunction());
System.out.println(AviatorEvaluator.execute("add(1, 2)")); // 3.0
System.out.println(AviatorEvaluator.execute("add(add(1, 2), 100)")); // 103.0
}
}
class AddFunction 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());
}
public String getName() {
return "add";
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
AviatorEvaluator.addFunctionremoveFunction
编译表达式
env
public class TestAviator {
public static void main(String[] args) {
String expression = "a-(b-c)>100";
// 编译表达式
Expression compiledExp = AviatorEvaluator.compile(expression);
Map<String, Object> env = new HashMap<String, Object>();
env.put("a", 100.3);
env.put("b", 45);
env.put("c", -199.100);
// 执行表达式
Boolean result = (Boolean) compiledExp.execute(env);
System.out.println(result); // false
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
compileExpressionenvExpressionexecute>!=、==、>、>=、<、<=String、Pattern、Booleanjava.lang.Comparable
AviatorEvaluator
public static Expression compile(String expression, boolean cached)
- 1
cachedtrue
public static void invalidateCache(String expression)
- 1
方法。
访问数组和集合
java.util.Listmap.keyjava.util.Mapkeyvalue
public static void main(String[] args) {
final List<String> list = new ArrayList<String>();
list.add("hello");
list.add(" world");
final int[] array = new int[3];
array[0] = 0;
array[1] = 1;
array[2] = 3;
final Map<String, Date> map = new HashMap<String, Date>();
map.put("date", new Date());
Map<String, Object> env = new HashMap<String, Object>();
env.put("list", list);
env.put("array", array);
env.put("mmap", map);
System.out.println(AviatorEvaluator.execute("list[0]+list[1]", env)); // hello world
System.out.println(AviatorEvaluator.execute("'array[0]+array[1]+array[2]=' + (array[0]+array[1]+array[2])", env)); // array[0]+array[1]+array[2]=4
System.out.println(AviatorEvaluator.execute("'today is ' + mmap.date ", env)); // today is Wed Feb 24 17:31:45 CST 2016
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
三元操作符
if else?:
AviatorEvaluator.exec("a>0? 'yes':'no'", 1); // yes
- 1
Aviator 的三元表达式对于两个分支的结果类型并不要求一致,可以是任何类型,这一点与 java 不同。
正则表达式匹配
=~
public static void main(String[] args) {
String email = "[email protected]";
Map<String, Object> env = new HashMap<String, Object>();
env.put("email", email);
String username = (String) AviatorEvaluator.execute("email=~/([\\w0-8]+)@\\w+[\\.\\w+]+/ ? $1 : 'unknow' ", env);
System.out.println(username); // killme2008
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
email/([\\w0-8]+@\\w+[\\.\\w+]+)/=~Boolean$1unknown
//=~$num的变量中,其中$0$1
java.util.regex.Pattern
变量的语法糖
aba.ba.b.cabcTestAviatorJavaBeanpublic
public class TestAviator {
int i;
float f;
Date date;
// 构造方法
public TestAviator(int i, float f, Date date) {
this.i = i;
this.f = f;
this.date = date;
}
// getter and setter
public static void main(String[] args) {
TestAviator foo = new TestAviator(100, 3.14f, new Date());
Map<String, Object> env = new HashMap<String, Object>();
env.put("foo", foo);
System.out.println(AviatorEvaluator.execute("'foo.i = '+foo.i", env)); // foo.i = 100
System.out.println(AviatorEvaluator.execute("'foo.f = '+foo.f", env)); // foo.f = 3.14
System.out.println(AviatorEvaluator.execute("'foo.date.year = '+(foo.date.year+1990)", env)); // foo.date.year = 2106
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
nil 对象
nilnullnilnullnull==、!=nil>、>=、<、<=nilnilnullnil
AviatorEvaluator.execute("nil == nil"); //true
AviatorEvaluator.execute(" 3> nil"); //true
AviatorEvaluator.execute(" true!= nil"); //true
AviatorEvaluator.execute(" ' '>nil "); //true
AviatorEvaluator.execute(" a==nil "); //true, a 是 null
- 1
- 2
- 3
- 4
- 5
nilStringnull
日期比较
java.util.DateDate
public static void main(String[] args) {
Map<String, Object> env = new HashMap<String, Object>();
final Date date = new Date();
String dateStr = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SS").format(date);
env.put("date", date);
env.put("dateStr", dateStr);
Boolean result = (Boolean) AviatorEvaluator.execute("date==dateStr", env);
System.out.println(result); // true
result = (Boolean) AviatorEvaluator.execute("date > '2010-12-20 00:00:00:00' ", env);
System.out.println(result); // true
result = (Boolean) AviatorEvaluator.execute("date < '2200-12-20 00:00:00:00' ", env);
System.out.println(result); // true
result = (Boolean) AviatorEvaluator.execute("date==date ", env);
System.out.println(result); // true
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
StringStringniljava.util.Date
大数计算和精度
java.math.BigIntegerjava.math.BigDecimalbig intdecimal99999999999999999999999999999999LongBigInteger
public static void main(String[] args) {
System.out.println(AviatorEvaluator.exec("99999999999999999999999999999999 + 99999999999999999999999999999999"));
}
- 1
- 2
- 3
big int199999999999999999999999999999998
字面量表示
big intdecimal
Nbig int1N,2N,9999999999999999999999Nbig intlongbig intMdecimal1M,2.222M, 100000.9999Mdecimal用户也可以通过变量传入这两种类型来参与计算。
运算
big intdecimallong,double
public static void main(String[] args) {
Object rt = AviatorEvaluator.exec("9223372036854775807100.356M * 2");
System.out.println(rt + " " + rt.getClass()); // 18446744073709551614200.712 class java.math.BigDecimal
rt = AviatorEvaluator.exec("92233720368547758074+1000");
System.out.println(rt + " " + rt.getClass()); // 92233720368547759074 class java.math.BigInteger
BigInteger a = new BigInteger(String.valueOf(Long.MAX_VALUE) + String.valueOf(Long.MAX_VALUE));
BigDecimal b = new BigDecimal("3.2");
BigDecimal c = new BigDecimal("9999.99999");
rt = AviatorEvaluator.exec("a+10000000000000000000", a);
System.out.println(rt + " " + rt.getClass()); // 92233720368547758089223372036854775807 class java.math.BigInteger
rt = AviatorEvaluator.exec("b+c*2", b, c);
System.out.println(rt + " " + rt.getClass()); // 20003.19998 class java.math.BigDecimal
rt = AviatorEvaluator.exec("a*b/c", a, b, c);
System.out.println(rt + " " + rt.getClass()); // 2.951479054745007313280155218459508E+34 class java.math.BigDecimal
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
类型转换和提升
big intdecimallong < big int < decimal < double
1 + 3Nbig int4N1 + 3.1Mdecimal4.1M1N + 3.1Mdecimal4.1M1.0 + 3Ndouble4.01.0 + 3.1Mdouble4.1decimal 的计算精度
java.math.BigDecimaljava.math.MathContextdecimal
MathContext.DECIMAL128
AviatorEvaluator.setMathContext(MathContext.DECIMAL64);
- 1
decimaljava.math.BigDecimal
强大的 seq 库
seqjava.util.Collectionseqseq
list
public static void main(String[] args) {
Map<String, Object> env = new HashMap<String, Object>();
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(20);
list.add(10);
env.put("list", list);
Object result = AviatorEvaluator.execute("count(list)", env);
System.out.println(result); // 3
result = AviatorEvaluator.execute("reduce(list,+,0)", env);
System.out.println(result); // 33
result = AviatorEvaluator.execute("filter(list,seq.gt(9))", env);
System.out.println(result); // [10, 20]
result = AviatorEvaluator.execute("include(list,10)", env);
System.out.println(result); // true
result = AviatorEvaluator.execute("sort(list)", env);
System.out.println(result); // [3, 10, 20]
AviatorEvaluator.execute("map(list,println)", env);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
我们可以:
count(list)reduce(list,+,0)reduceseq+filter(list,seq.gt(9))list9seq.gtinclude(list,10)sort(list)map(list,println)mapprintln两种运行模式
AviatorEvaluator
AviatorEvaluator.setOptimize(AviatorEvaluator.EVAL);
- 1
你可以修改为编译速度优先,这样不会做编译优化:
AviatorEvaluator.setOptimize(AviatorEvaluator.COMPILE);
- 1
调试信息
tracetrue
AviatorEvaluator.setTrace(true);
- 1
方便用户做跟踪和调试。默认是输出到标准输出,你可以改变输出指向:
AviatorEvaluator.setTraceOutputStream(new FileOutputStream(new File("aviator.log")));
- 1
语法手册
下面是 Aviator 详细的语法规则定义。
数据类型
Numberlong,double,java.math.BigInteger(简称 big int)java.math.BigDecimal(简 称 decimal)Nbig intMdecimalLongDoublelongbig intbig intdecimal0x0X1e-3
String'hello world'StringCharacterStringBooltruefalseBoolean.TRUEBoolean.FalsePattern///\d+/java.util.Patternnilnilnullnilnil==、!=>、>=、<、<=nilnilnil==niltruenullnilnilnull操作符
算术运算符
+ - * / %-(负)- * / %-Number+NumberStringStringString
逻辑运算符
!&&||Boolean&&||
关系运算符
<, <=, >, >===!=NumberStringPatternBooleannilnil
位运算符
&, |, ^, ~, >>, <<, >>>
匹配运算符
=~StringPatternStringPatternPattern$numnum
三元运算符
if else?:bool ? exp1: exp2boolBooleanexp1exp2exp1exp2
内置函数
| 函数名称 | 说明 |
|---|---|
| sysdate() | 返回当前日期对象 java.util.Date |
| rand() | 返回一个介于 0-1 的随机数,double 类型 |
| print([out],obj) | 打印对象,如果指定 out,向 out 打印, 否则输出到控制台 |
| println([out],obj) | 与 print 类似,但是在输出后换行 |
| now() | 返回 System.currentTimeMillis |
| long(v) | 将值的类型转为 long |
| double(v) | 将值的类型转为 double |
| str(v) | 将值的类型转为 string |
| date_to_string(date,format) | 将 Date 对象转化化特定格式的字符串,2.1.1 新增 |
| string_to_date(source,format) | 将特定格式的字符串转化为 Date 对 象,2.1.1 新增 |
| string.contains(s1,s2) | 判断 s1 是否包含 s2,返回 Boolean |
| string.length(s) | 求字符串长度,返回 Long |
| string.startsWith(s1,s2) | s1 是否以 s2 开始,返回 Boolean |
| string.endsWith(s1,s2) | s1 是否以 s2 结尾,返回 Boolean |
| string.substring(s,begin[,end]) | 截取字符串 s,从 begin 到 end,如果忽略 end 的话,将从 begin 到结尾,与 java.util.String.substring 一样。 |
| string.indexOf(s1,s2) | java 中的 s1.indexOf(s2),求 s2 在 s1 中 的起始索引位置,如果不存在为-1 |
| string.split(target,regex,[limit]) | Java 里的 String.split 方法一致,2.1.1 新增函数 |
| string.join(seq,seperator) | 将集合 seq 里的元素以 seperator 为间隔 连接起来形成字符串,2.1.1 新增函数 |
| string.replace_first(s,regex,replacement) | Java 里的 String.replaceFirst 方法, 2.1.1 新增 |
| string.replace_all(s,regex,replacement) | Java 里的 String.replaceAll 方法 , 2.1.1 新增 |
| math.abs(d) | 求 d 的绝对值 |
| math.sqrt(d) | 求 d 的平方根 |
| math.pow(d1,d2) | 求 d1 的 d2 次方 |
| math.log(d) | 求 d 的自然对数 |
| math.log10(d) | 求 d 以 10 为底的对数 |
| math.sin(d) | 正弦函数 |
| math.cos(d) | 余弦函数 |
| math.tan(d) | 正切函数 |
| map(seq,fun) | 将函数 fun 作用到集合 seq 每个元素上, 返回新元素组成的集合 |
| filter(seq,predicate) | 将谓词 predicate 作用在集合的每个元素 上,返回谓词为 true 的元素组成的集合 |
| count(seq) | 返回集合大小 |
| include(seq,element) | 判断 element 是否在集合 seq 中,返回 boolean 值 |
| sort(seq) | 排序集合,仅对数组和 List 有效,返回排 序后的新集合 |
| reduce(seq,fun,init) | fun 接收两个参数,第一个是集合元素, 第二个是累积的函数,本函数用于将 fun 作用在集合每个元素和初始值上面,返回 最终的 init 值 |
| seq.eq(value) | 返回一个谓词,用来判断传入的参数是否跟 value 相等,用于 filter 函数,如filter(seq,seq.eq(3)) 过滤返回等于3 的元素组成的集合 |
| seq.neq(value) | 与 seq.eq 类似,返回判断不等于的谓词 |
| seq.gt(value) | 返回判断大于 value 的谓词 |
| seq.ge(value) | 返回判断大于等于 value 的谓词 |
| seq.lt(value) | 返回判断小于 value 的谓词 |
| seq.le(value) | 返回判断小于等于 value 的谓词 |
| seq.nil() | 返回判断是否为 nil 的谓词 |
| seq.exists() | 返回判断不为 nil 的谓词 |