开发者

Castor XML Mapping and java.util.Map

I've been using Castor these past couple of days to try to get a little serialization going between my Java program and XML in a readable way. Though it has a few faults, Castor's automatic xml generation via reflection is actually very functional. Unfortunately, one thing that seems to be fairly well left out of the examples is dealing with generics. It seems the reflection API does a wonderful job as it is开发者_StackOverflow, but as it is inadvertently grabbing a lot of redundant data just because methods start with get___(), I wanted to write my own mapping file to stave this off.

Firstly, it seems altogether fair that in the attributes to a "field" element, one should define "type". However, it does not specify what should be done if this type is abstract or simply an interface. What should I put as the type then?

Secondly, most "collection" type objects specified in Castor (List, Vector, Collection, Set, etc) only require 1 generic type, so specifying "type" as what's inside and "collection="true"" are enough. However, it does not specify what I should do in the case of a collection like a Map, where 2 types are necessary. How can I specify both the key type and value type?

Any help at all would be greatly appreciated!


For the second of my questions:

When specifying something with a Map or a Table, you need to redefine org.exolab.castor.mapping.MapItem within the bind-xml element within your field element. Example taken from here

<class name="some.example.Clazz">
  <field name="a-map" get-method="getAMap" set-method="setAMap">
    <bind-xml ...>
       <class name="org.exolab.castor.mapping.MapItem">
          <field name="key" type="java.lang.String">
            <bind-xml name="id"/>
          </field>
          <field name="value" type="com.acme.Foo"/>
       </class>
    </bind-xml>
  </field>
</class>

Also, omit the type attribute from the parent field element.


For my first question, the trick is to NOT specify the type in the field element and allow Castor to infer it by itself. If you have definitions for the classes that could appear there, then it will automatically use those. For example:

<class name="some.example.Clazz">
    <!-- can contain condition1 or condition2 elements -->
    <field name="condition" collection="arraylist" required="true">
        <bind-xml name="condition" node="element" />
    </field>
</class>  

<class name="some.example.condition1">
    <field name="oneField" >
        <xml-bind name="fieldOne" />
    </field>
</class>

<class name="some.example.condition2">
    <field name="anotherField />
        <xml-bind name="fieldTwo" />
    </field>
</class>

The output of into XML by Castor would use condition1 and condition2 style XML into the "condition" field of Clazz while still referring to its proper instantiation type.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜