移:扩展OGNL

扩展OGNL
OGNL会自动把字符串内容树映射到对象树中。但是对于空对象必须自己做处理,处理方法是继承NullHandler接口,下面的例子会自动创建空对象。但是对于List等还未作处理
 
public class TestOGNL {
 
    public static void main(String[] args) throws Exception {
        try {
            Action action = new Action();
            OgnlRuntime.setNullHandler(Object.class, new StanderNullHandler());
            Ognl.setValue("main.id", action, "001");
            Object result = Ognl.getValue("main.id", action);
            System.out.println("Test:" + result);
        } catch (OgnlException e) {
            e.printStackTrace();
        }
    }
}
class StanderNullHandler implements NullHandler {
    public StanderNullHandler() {
        super();
    }
    public Object nullMethodResult(Map context, Object target, String methodName, Object[] args) {
        return null;
    }
    public Object nullPropertyValue(Map context, Object target, Object property) {
        try {
            String propName = property.toString();
            Class clazz = OgnlRuntime.getPropertyDescriptor(target.getClass(), propName).getPropertyType();
            Object param = clazz.newInstance();//这里会新建实例
            System.out.println(param);
            Ognl.setValue(propName, context, target, param);//这里会是递归调用?
            return param;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
class Action {
    private String name;
    private List users = new ArrayList();
    public Main main;
    /**
     * @return Returns the main.
     */
    public Main getMain() {
        return main;
    }
    /**
     * @param main
     *            The main to set.
     */
    public void setMain(Main main) {
        this.main = main;
    }
    public Action() {
        users.add("yyy");
    }
    /**
     * @return Returns the users.
     */
    public List getUsers() {
        return users;
    }
    /**
     * @param users
     *            The users to set.
     */
    public void setUsers(List users) {
        this.users = users;
    }
    /**
     * @return Returns the name.
     */
    public String getName() {
        return name;
    }
    /**
     * @param name
     *            The name to set.
     */
    public void setName(String name) {
        this.name = name;
    }
}
class Main {
    private String id;
    /**
     * @return Returns the id.
     */
    public String getId() {
        return id;
    }
    /**
     * @param id
     *            The id to set.
     */
    public void setId(String id) {
        this.id = id;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值