2

I'm trying to implement inheritance with @XmlSeeAlso annotation. Everything works as expected when using different root node names for subclasses. But with the same root names Unmarshaller always choses the last class from the XmlSeeAlso list despite of the content. It's impossible to change root names. Is where any way to make Unmarshaller to chose class correctly by content?

import java.io.ByteArrayInputStream;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.transform.stream.StreamSource;

import org.springframework.oxm.jaxb.Jaxb2Marshaller;

public class Test {
  public static void main(String[] args) {
    Jaxb2Marshaller unmarshaller = new Jaxb2Marshaller();
    unmarshaller.setClassesToBeBound(Parent.class);
    System.out.println(unmarshaller.unmarshal(new StreamSource(
        new ByteArrayInputStream("<value><a>AAA</a><b>BBB</b></value>"
            .getBytes()))));
    System.out.println(unmarshaller.unmarshal(new StreamSource(
        new ByteArrayInputStream("<value><c>CCC</c><d>DDD</d></value>"
            .getBytes()))));
  }

  @XmlSeeAlso({ ChildAB.class, ChildCD.class })
  public static abstract class Parent {
  }

  @XmlRootElement(name = "value")
  public static class ChildAB {
    @XmlElement(name = "a")
    private String a;
    @XmlElement(name = "b")
    private String b;

    @Override
    public String toString() {
      return "ChildAB[" + a + "; " + b + "]";
    }
  }

  @XmlRootElement(name = "value")
  public static class ChildCD {
    @XmlElement(name = "c")
    private String c;
    @XmlElement(name = "d")
    private String d;

    @Override
    public String toString() {
      return "ChildCD[" + c + "; " + d + "]";
    }
  }
}

Output:

ChildCD[null; null]
ChildCD[CCC; DDD]
Xstian
  • 8,184
  • 10
  • 42
  • 72
Tanya
  • 21
  • 1

1 Answers1

0

Why your class ChildAB and ChildCD are static? Also ChildAB and ChildCD should implement/extend your Parent class.

Iman M
  • 33
  • 1
  • 7
  • Classes ChildAB and ChildCD are inner for the sake of brevity. If they were not static, it whould be impossible to use them for unmarshalling, because they couldn't be instantiated without enclosing class instance. You are right, they should extend parent class, though it doesn't metter in the context of the issue. SeeAlso annotation does nothing with inheritance – Tanya Dec 08 '15 at 10:23