首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

透过java反射简单实现ognl原理

2012-10-09 
通过java反射简单实现ognl原理/*?* 模拟实现ognl表达式?*/public class MyOgnlValue {?// 用迭代

通过java反射简单实现ognl原理

/*
?* 模拟实现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;
?}

?}

热点排行