Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@XmlElementRefs & @XmlElementRef annotations in Java

Tags:

java

xml

jaxb

Can some please explain to me what do

@XmlElementRefs

and

@XmlElementRef

annotations mean in Java and what is their use..

EDIT: @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 else constructs?

like image 457
Aaron S Avatar asked Jan 27 '10 08:01

Aaron S


1 Answers

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

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

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

like image 70
skaffman Avatar answered Oct 18 '22 21:10

skaffman