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

我有一个像这样的XML文件:

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


我还有另一个bean,它包含一个“ attribute”标签(但在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;
}


XmlGlobal保留为<global>标签

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。

准确地说:XmlTargetExcludedAttribute和XmlTargetAttribute类只是为了易于阅读而相同,实际上是不同的。

我该如何解释要使用的课程?

最佳答案

您可以在每个列表值的属性上注册一个本地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;
}

关于java - XSTREAM-类强制转换异常,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28940683/

10-12 16:07