1

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

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

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

4

2 回答 2

-1

这是程序化方式的示例:

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)])
于 2017-03-20T12:23:53.510 回答
-1

我认为,正如马克所说,注释不可能做到这一点(在网络上找不到任何东西)。在我的特殊情况下,作为一个walkarround,我所做的是从基类(Vivek 示例中的ABC)扩展并将它们自己的注释放在子类中并使用这些类。解决方案取决于您的代码实现。问候。-

ABC班

@XStreamAlias("alias1") DFG 扩展 ABC

@XStreamAlias("alias2") XYZ 扩展 ABC

于 2017-12-01T16:14:57.573 回答