/*
* 模拟实现ognl表达式
*/
public class MyOgnlValue {
// =========用迭代的方式解决多参数问题========================//
public static Object getValue(String exp, MyContext root) throws Exception {
if (exp == null || exp.length() == 0) {
throw new Exception("表达式为空!");
}
String[] express = exp.split("\\.");
if (express.length == 1) {
return root.get(express);
} else {
Object o = root.get(express[0]);
int i = 1;
while (express.length != i) {
o=getValue(express[i], o);
i++;
}
return o;
}
}
public static Object getValue(String exp, Object o) throws Exception {
String md="";
Object obj=null;
if(exp.indexOf("[")>0)
{
md="get"+exp.substring(0,1).toUpperCase()+exp.substring(1,exp.indexOf("["));
Method method=o.getClass().getMethod(md, new Class[]{});
obj= method.invoke(o, new Object[]{});
if(obj instanceof List)
{
int j=Integer.parseInt(exp.substring(exp.indexOf("[")+1,exp.indexOf("]")));
return ((List) obj).get(j);
}
else if(obj instanceof Map)
{
String key=exp.split("\'")[1];
return ((Map) obj).get(key);
}
else if(obj.getClass().getName().indexOf("[L")==0 || obj.getClass().isArray())
{
int j=Integer.parseInt(exp.substring(exp.indexOf("[")+1,exp.indexOf("]")));
return Array.get(obj, j);
}
}
else
{
md="get"+exp.substring(0,1).toUpperCase()+exp.substring(1);
Method method=o.getClass().getMethod(md, new Class[]{});
obj=method.invoke(o, new Object[]{});
return obj;
}
return obj;
}
}