App下載
首頁javajaxbJava HTML/XML - 如何使用@XmlTransient綁定JAXB抽象類

Java HTML/XML - 如何使用@XmlTransient綁定JAXB抽象類

我們想知道如何使用@XmlTransient綁定JAXB抽象類。
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;

public class Main {

  public static void main(String[] args) throws Exception {
    JAXBContext jc = JAXBContext.newInstance(Bar.class);

    Bar bar = new Bar();
    bar.setAtt1("a");
    bar.setAtt2("b");

    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(bar, System.out);
  }

  @XmlTransient
  public static class Foo {

    private String att1;
    private String att2;

    @XmlAttribute
    public String getAtt1() {
      return att1;
    }

    public void setAtt1(String att1) {
      this.att1 = att1;
    }

    public String getAtt2() {
      return att2;
    }

    public void setAtt2(String att2) {
      this.att2 = att2;
    }

  }

  @XmlRootElement
  public static class Bar extends Foo {

    @Override
    @XmlAttribute
    public String getAtt2() {
      return super.getAtt2();
    }

    @Override
    public void setAtt2(String att2) {
      super.setAtt2(att2);
    }

  }
}