Java 中的 @XmlElementRefs 和 @XmlElementRef 注释

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2145378/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 19:40:08  来源:igfitidea点击:

@XmlElementRefs & @XmlElementRef annotations in Java

javaxmljaxb

提问by 6pack kid

Can some please explain to me what do

可以请一些人向我解释做什么

@XmlElementRefs

and

@XmlElementRef

annotations mean in Java and what is their use..

注释在 Java 中的含义以及它们的用途..

EDIT:@skaffman

编辑:@skaffman

okay, suppose I have one such collection

好吧,假设我有一个这样的收藏

@XmlElementRefs({
    @XmlElementRef(name="ElementA", type=ClassA),
    @XmlElementRef(name="ElementB", type=ClassB) }
)

List<Object> items;

Now how do I access every individual element of this list? Is the following code correct?

现在如何访问此列表的每个单独元素?下面的代码正确吗?

for (int j = 0; j < items.size(); ++j) {
    if (items.get(i).getClass().equals(ClassA)) {
        // perform ClassA specific processing:
    } else if (items.get(i).getClass().equals(ClassB)) {
        // perform ClassB specific processing:
    }
}

Is this correct approach? Is there a better way to perform each class specific processing? I mean is there a way to avoid those if elseconstructs?

这是正确的方法吗?有没有更好的方法来执行每个类的特定处理?我的意思是有没有办法避免这些if else结构?

采纳答案by skaffman

These are used to annotate a collection which can contain various different types. The java binding for such a list is:

这些用于注释可以包含各种不同类型的集合。这种列表的 java 绑定是:

@XmlElementRefs({
   @XmlElementRef(name="ElementA", type=ClassA),
   @XmlElementRef(name="ElementB", type=ClassB)
})
List<Object> items

Here, itemscan contain an arbitrary mix of ClassAand ClassB, and since that can't be expressed in List's type signature, it has to be expressed using annotations.

在这里,items可以包含任意组合ClassAClassB,而且由于不能在表达List的类型签名,它使用注释来表达。