Castor XML mapping and java.util.Map

I used Castor in the last couple of days to try and get a little serialization between my Java program and XML in a readable way. Although it has several drawbacks, the automatic generation of xml Castor through reflection is actually very functional. Unfortunately, one thing that does not seem to be mentioned quite well in the examples is generics. The reflection API seems to do the job fine, but since it inadvertently captures a lot of redundant data just because the methods start with get___(), I wanted to write my own mapping file to prevent this.

Firstly, it seems quite fair that the " field" should be defined in the attributes of the " " element type. However, it does not indicate what should be done if this type is abstract or just an interface. What should I put as a type?

Secondly, the majority of objects of type "collection" specified in Castor ( List, Vector, Collection, Setetc.), require only one common type, therefore specify " type" such as that inside and " collection="true"" enough. However, it does not indicate what I should do in the case of a type collection Mapwhere 2 types are needed. How to specify the type and type of key?

Any help at all would be greatly appreciated!

+3
source share
2 answers

For the second of my questions:

When specifying something with a map or table, you need to override org.exolab.castor.mapping.MapItemin the element bind-xmlin the element field. Example 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 attribute typefrom the parent element field.

+2
source

In my first question, the trick is NOT to specify the type in the field element and let Castor output it by itself. If you have definitions for classes that may appear there, then they will automatically use them. For instance:

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

Castor's XML output will use the XML conditions condition1 and condition2 in the Clazz condition field, still referring to its own type of instantiation.

+1
source

Source: https://habr.com/ru/post/1753585/


All Articles