我可以使用 OGNL 动态创建对象和设置属性吗? [英] Can I use OGNL to dynamically create objects and set properties?

查看:38
本文介绍了我可以使用 OGNL 动态创建对象和设置属性吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个系统,用于将接收到的结构化消息动态映射到 Java 对象.目前我正在通过 XML 模式执行此操作,该模式具有以下典型格式:

I'm developing a system for dynamically mapping received structured messages to Java objects. Currently I'm doing this via an XML schema, which has the following typical format:

<mapping>
  <domainObject>company.app.MyObject</domainObject>
  <attribute>
    <domainAttribute>myAttr</domainAttribute>
    <messageAttribute>root/config/component/param1</messageAttribute>
  </attribute>
</mapping>

因此接收到的消息具有层次结构,映射到特定的域对象属性.因此,对于上述内容,我将消息元素 root/config/component/param1 映射到域属性 MyObject.myAttr

So the received message has a hierarchical structure, which maps on to specific domain object attributes. So for the above, I'm mapping message element root/config/component/param1 on to domain attribute MyObject.myAttr

我已经开发了代码来做到这一点,但是在阅读了 Struts2 及其对 OGNL 的使用之后,它似乎在做同样的事情.我的问题是,OGNL 能否动态构造必要的对象,然后填充所有必要的属性?如果是这样,那是如何完成的? 从阅读 API 文档来看,您似乎必须自己构造对象.例如,如果我使用这样的 OGNL 表达式

I've already developed code to do this, but after reading about Struts2 and its use of OGNL, it seems like it's doing the same thing. My question is, can OGNL dynamically construct the necessary objects, followed by populating all necessary attributes? If so, how is that done? From reading the API docs, it seems that you must construct the objects yourself. For example if I used an OGNL expression like this

rootObj.childObj.param1

理想情况下,我希望 OGNL 服务构造对象 rootObj,然后是 childObj,然后设置属性 param1.这正是 Struts 将 Http 请求参数传递给域对象所做的工作,因此动态对象创建必须在某处发生.然而,在对 OGNL 表达式进行了一些试验后,没有发生对象创建,并且我得到了空对象异常.

Ideally I'd want the OGNL service to construct object rootObj, followed by childObj, then set attribute param1. This is exactly what Struts does to transfer Http request parameters on to domain objects, so dynamic object creation must be happening somewhere. However after doing some experimenting with OGNL expressions, there's no object creation happening, and I get null object exceptions.

推荐答案

OGNL 不会构造您的对象.它主要用于并最终用于评估表达式.创建对象是您或使用 ObjectFactory 来创建对象.

OGNL will not construct your objects. It's used primarily and eventually to evaluate expressions. Creating objects is the responsibility by you or framework that used ObjectFactory to create objects.

这篇关于我可以使用 OGNL 动态创建对象和设置属性吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆