如何在同一元素上使用多个@XStreamAlias批注。当我这样做时:

@XStreamAlias("alias1")
@XStreamAlias("alias2")
class ABC{
//
}


我得到编译错误。有什么办法可以做到这一点?

最佳答案

这是编程方式的示例:

import java.io.InputStream;
import java.util.List;

import org.junit.Test;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;

import lombok.Data;


public class MultiAlias {

    @Test
    public void smokeTest() {
        InputStream file = MultiAlias.class.getResourceAsStream("MultiAliasTest.xml");
        XStream xStream = new XStream();
        xStream.ignoreUnknownElements();
        xStream.processAnnotations(Parent.class);
        xStream.alias("child", Child.class);
        xStream.alias("kind", Child.class);

        Parent parent = (Parent) xStream.fromXML(file);

        System.out.println(parent);
    }

    @XStreamAlias("parent")
    @Data
    public class Parent {

        @XStreamAsAttribute
        private String name;

        private List<Child> children;

    }

    @Data
    public class Child {
        private String name;
    }

}


XML:

<?xml version="1.0" encoding="UTF-8"?>
<parent name="Adam">
        <age>33</age>
        <children>
            <child>
                <name>Iva</name>
            </child>
            <kind>
                <name>Peter</name>
            </kind>
        </children>
</parent>


输出:

MultiAlias.Parent(name=Adam, children=[MultiAlias.Child(name=Iva), MultiAlias.Child(name=Peter)])

08-05 04:44