Jexl 是一个 Expression Language 的解析引擎, 是为了方便嵌入你的系统或者程序框架的开发中, 他算是实现了 JSTL 中 EL 的延伸版本. 不过也采用了一些 Velocity 的概念. 下面是一个使用Jexl的例子,有详细注释,
- import java.util.HashMap;
- import java.util.List;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Map;
- import org.apache.commons.jexl.Expression;
- import org.apache.commons.jexl.ExpressionFactory;
- import org.apache.commons.jexl.JexlContext;
- import org.apache.commons.jexl.JexlHelper;
- ......
- /*
- * 初始化一个Cat对象
- */
- Cat cat = new Cat() {
- {
- this.setAge(2);
- this.setName("Tom");
- this.setOwner(new People() {
- {
- this.setAge(24);
- this.setName("yang");
- }
- });
- }
- };
- /*
- * 初始化一个List对象,列表里存入两个元素
- * 第一个元素是一个字符串
- * 第二个元素是一个整数
- */
- List list = new ArrayList();
- list.add("Hello world !");
- list.add(11);
- Map map = new HashMap();
- map.put("cat", cat);
- map.put("people",cat.getOwner());
- /*
- * 初始化一个JexlContext对象,它代表一个执行JEXL表达式的上下文环境
- */
- JexlContext context = JexlHelper.createContext();
- /*
- * 向执行JEXL表达式的上下文环境的变量字典中存入两个变量
- * 键值 "tom" 对应变量 cat
- * 键值 "array" 对应变量 list
- */
- context.getVars().put("tom", cat);
- context.getVars().put("array", list);
- context.getVars().put("map", map);
- /*
- * 定义要被求值的所有表达式
- */
- String[] expressions = new String[]{
- //嵌套属性
- "tom.owner",
- //嵌套属性
- "tom.owner.name",
- //嵌套属性的方法调用,表达式求值结果为方法返回值
- "tom.owner.name.length()",
- "array[0].toUpperCase()",
- //内置通用方法size(),返回String,Map和List的长度
- "size(tom.owner.name)",
- //返回列表中第一个元素
- "array[0]",
- //+ 操作符 可用于字符串的连接
- "array[0].toUpperCase()+array[0]",
- //内置通用方法empty(),如果为空返回true,否则返回false
- "empty(array[0])",
- "empty(array[2])",
- //通过键值 'cat' 获取字典中相应的值
- "map['cat']",
- //嵌套属性
- "map['people'].name.length()"
- };
- //对 expressions 中所有的表达式求值
- for(String expression : expressions){
- //用ExpressionFactory类的静态方法createExpression创建一个Expression对象
- Expression e = ExpressionFactory.createExpression(expression);
- //对这个Expression对象求值,传入执行JEXL表达式的上下文环境对象
- Object obj = e.evaluate(context);
- //输出表达式求值结果
- System.out.println(e.getExpression()+" = "+obj);
- }
运行结果如下:
tom.owner = testJexl.Test_1$1$1@1ffbd68
tom.owner.name = yang
tom.owner.name.length() = 4
array[0].toUpperCase() = HELLO WORLD !
size(tom.owner.name) = 4
array[0] = Hello world !
array[0].toUpperCase()+array[0] = HELLO WORLD !Hello world !
empty(array[0]) = false
empty(array[2]) = true
map['cat'] = testJexl.Test_1$1@179c285
map['people'].name.length() = 4
http://yangjunfeng.iteye.com/blog/399602