Search code examples
javaxmlxstream

XSTREAM - class cast exception


i have a problem easy to understand hard to fix (for me).

I have an XML file like this:

    <class name='package.AnnotatedClass2'>
      <attribute name='field1'>
        <attributes>
          <attribute name='targetField1name' />
          <attribute name='targetField2name' />
        </attributes>
      </attribute>
   </class>

I have another bean that contains an "attribute" tag (but not present in XML file), global node:

<class name="package.Example">
    <global>
        <excluded>
           <attribute name ="field3"/>
        </excluded>
    </global>
  </class>

XmlClass that stay for <class> tag

public class XmlClass {

    /** global configuration */
    public XmlGlobal global;
    /** list of attributes node */
    @XStreamImplicit(itemFieldName="attribute")
    public List<XmlAttribute> attributes;
}

XmlGlobal that stay for <global> tag

public class XmlGlobal {
   public List<XmlTargetExcludedAttribute> excluded;
}

@XStreamAlias("attribute")
public class XmlTargetExcludedAttribute {
   /** name attribute of class node */
   @XStreamAsAttribute
   public String name;
}

And XmlAttribute:

public class XmlAttribute {

   /** list of target attributes */
    public List<XmlTargetAttribute> attributes;
}

@XStreamAlias("attribute")
public class XmlTargetAttribute {

   /** name attribute of attribute node */
   @XStreamAsAttribute
   public String name;
}

After perfoming the toXml() method in xmlAttribute.attributes i have two instances of XmlTargetExcludedAttribute instead of XmlTargetAttribute.

to be precise: the classes XmlTargetExcludedAttribute and XmlTargetAttribute are identical only for ease of reading, in fact they are different.

how can I explain that class to use?


Solution

  • Rather than aliasing the two different classes globally, you could register a local NamedCollectionConverter on each of the List-valued properties:

    public class XmlGlobal {
       @XStreamConverter(value=NamedCollectionConverter.class, useImplicitType=false,
          strings={"attribute"}, types={XmlTargetExcludedAttribute.class})
       public List<XmlTargetExcludedAttribute> excluded;
    }
    
    public class XmlTargetExcludedAttribute {
       /** name attribute of class node */
       @XStreamAsAttribute
       public String name;
    }
    
    
    public class XmlAttribute {
    
       /** list of target attributes */
       @XStreamConverter(value=NamedCollectionConverter.class, useImplicitType=false,
          strings={"attribute"}, types={XmlTargetAttribute.class})
       public List<XmlTargetAttribute> attributes;
    }
    
    public class XmlTargetAttribute {
    
       /** name attribute of attribute node */
       @XStreamAsAttribute
       public String name;
    }