Search code examples
javaxmlstruts2ognl

Can I use OGNL to dynamically create objects and set properties?


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>

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

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

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.


Solution

  • 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:

    All objects created by the framework are instantiated by the ObjectFactory. The ObjectFactory provides the means of integrating the framework with IoC containers like Spring, Pico, Plexus, and so forth.