14

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?

1
  • You usually use this with polymorphism. ClassA and ClassB both extend ClassBase, so you don't need if/else to dispatch correctly the processing.
    – ewernli
    Commented Jan 27, 2010 at 10:50

1 Answer 1

7

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.

5
  • 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: } else }
    – Aaron S
    Commented Jan 27, 2010 at 8:40
  • I can't read that. Please add it your question (and format it properly.)
    – skaffman
    Commented Jan 27, 2010 at 10:15
  • But the same also works with @XmlElements and @XmlElement, no?
    – ewernli
    Commented Jan 27, 2010 at 10:48
  • how would you set ElementA or B to something?
    – ant
    Commented May 17, 2010 at 12:28
  • Ok, I found difference: property annotated with @XmlElementRefs can contain descendant classes. <rs><a/><b/><suba/><subb/></rs> vs <es><a/><b/><suba xsi:type="suba" xmlns:xsi="w3.org/2001/XMLSchema-instance"/><subb xsi:type="subb" xmlns:xsi="w3.org/2001/XMLSchema-instance"/></es> Commented Nov 19, 2010 at 12:58

Not the answer you're looking for? Browse other questions tagged or ask your own question.