XSTREAM - class 转换异常

XSTREAM - class cast exception

我有一个容易理解却很难解决的问题(对我来说)。

我有一个这样的 XML 文件:

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

我有另一个包含 "attribute" 标记的 bean(但不存在于 XML 文件中),全局节点:

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

<class> 标记保留的 XmlClass

public class XmlClass {

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

<global> 标记保留的 XmlGlobal

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

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

和 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;
}

在 xmlAttribute.attributes 中执行 toXml() 方法后,我有两个 XmlTargetExcludedAttribute 实例而不是 XmlTargetAttribute。

准确地说:classes XmlTargetExcludedAttribute 和 XmlTargetAttribute 相同只是为了便于阅读,实际上它们是不同的。

如何解释 class 的使用?

与其在全局范围内为两个不同的 类 添加别名,不如在每个列表值属性上注册一个本地 NamedCollectionConverter

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