Java HTML / XML How to - Bind class hierarchy using JaxB








Question

We would like to know how to bind class hierarchy using JaxB.

Answer

//  www  .  ja  v  a 2s  . c  o m
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

public class Main {

  public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(A.class, B.class);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    A a = new A();
    a.setFoo("Hello World");
    marshaller.marshal(a, System.out);

    B b = new B();
    b.setFoo("Hello World");
    marshaller.marshal(b, System.out);
  }

  @XmlRootElement
  public static class A implements IntF {

    private String foo;

    @Override
    @XmlElement(name = "renamed-foo")
    public String getFoo() {
      return foo;
    }

    @Override
    public void setFoo(String foo) {
      this.foo = foo;
    }

  }

  @XmlRootElement
  public static class B implements IntF {

    private String foo;

    @Override
    @XmlAttribute
    public String getFoo() {
      return foo;
    }

    @Override
    public void setFoo(String foo) {
      this.foo = foo;
    }

  }

  public interface IntF {
    public String getFoo();

    public void setFoo(String foo);
  }
}