jstl中,可以这样写${a.b[0].c},那么系统自动从a对象中取出b数组(列表),取出第一个对象,并得到c属性。有没有这样的包,我传入一个对象和表达式,它自动根据表达式计算出值来。
比如我传入Obj和o.a.b[1].c
那么会自动从obj中得到a属性对象,并从a属性对象中得到b属性对象,b属性对象是一个数组或者列表,自动取出第二个,并得出它的c对象。
比如我传入Obj和o.a.b[1].c
那么会自动从obj中得到a属性对象,并从a属性对象中得到b属性对象,b属性对象是一个数组或者列表,自动取出第二个,并得出它的c对象。
public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
FieldTest a = new FieldTest();
a.testBeanUtils();
} private void testBeanUtils() throws IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
InerBean bean = new InerBean();
Object[] str = new Object[2];
Map map = new HashMap();
map.put("c", "result");
str[0] = "test";
str[1] = map;
bean.setA(str); System.out.println(PropertyUtils.getProperty(bean, "a[1].c"));
} public class InerBean { private Object a = null; public Object getA() {
return a;
}
public void setA(Object a) {
this.a = a;
}
}}
// Create an expression object
String jexlExp = "foo.innerFoo.bar()";
Expression e = ExpressionFactory.createExpression( jexlExp ); // Create a context and add data
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("foo", new Foo() ); // Now evaluate the expression, getting the result
Object o = e.evaluate(jc);
需要commons-jexl-1.0.jar
commons-logging.jar,因为Expression e = ExpressionFactory.createExpression( jexlExp );用到log4j,所以出现一些异常。
只要log4j.properties设置没问题,应该能正常运转。
package test.util;import org.apache.commons.jexl.Expression;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.jexl.ExpressionFactory;
import org.apache.commons.jexl.JexlContext;
import org.apache.commons.jexl.JexlHelper;public class ExecuteExpression {
private int a = 1232; /**
* @param args
*/
public static void main(String[] args) {
ExecuteExpression eEx = new ExecuteExpression();
try {
eEx.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} private void execute() throws Exception {
String jexlExp = "ex.print()";
// Create a context and add data
JexlContext jc = JexlHelper.createContext();
jc.getVars().put("ex", new ExecuteExpression() );
Expression e = ExpressionFactory.createExpression( jexlExp );
// Now evaluate the expression, getting the result
Object o = e.evaluate(jc);
}
private void print() {
System.out.print(this.a);
}}
import java.util.Map;
import org.mvel.MVEL;public class MVELTest {
public static void main(String[] args) {
String expression = "foobar > 99"; Map vars = new HashMap();
vars.put("foobar", new Integer(100));
// We know this expression should return a boolean.
Boolean result = (Boolean) MVEL.eval(expression, vars); if (result.booleanValue()) {
System.out.println("It works!");
}
}
}程序中所用到包可在以下地址找到
http://huifon.bokee.com/viewdiary.22768167.html