3

我正在使用XmlAdapter此博客文章中提出的不可变对象:http: //blog.bdoughan.com/2010/12/jaxb-and-immutable-objects.html。这工作正常,但不适用于对我的适配器中其他不可变对象的引用。有没有办法用 JAXB 处理这个问题?

下面有一个示例,如果此人的 xml 标记出现在引用此人的公司的 xml 标记之后,则该示例不起作用。

不可变对象:

@XmlJavaTypeAdapter(PersonAdapter.class)
public class Person {
  private final String id;
  private final String name;

  public Person(String id, String name) {
    this.id = id;
    this.name = name;
  }

  public String getId() {
    return id;
  }

  public String getName() {
    return name;
  }
}

@XmlJavaTypeAdapter(CompanyAdapter.class)
public class Company {
  private final String name;
  private final Person principal;

  public Company(String name, Person principal) {
    this.name = name;
    this.principal = principal;
  }

  public String getName() {
    return name;
  }

  public Person getPrincipal() {
    return principal;
  }
}

人员适配器:

public class PersonAdapter extends XmlAdapter<AdaptedPerson, Person> {
  public static class AdaptedPerson {
    @XmlID
    @XmlAttribute
    String id;
    @XmlAttribute
    String name;
  }

  @Override
  public AdaptedPerson marshal(Person v) throws Exception {
    AdaptedPerson a = new AdaptedPerson();
    a.id = v.getId();
    a.name = v.getName();
    return a;
  }

  @Override
  public Person unmarshal(AdaptedPerson v) throws Exception {
    return new Person(v.id, v.name);
  }
}

公司适配器:

public class CompanyAdapter extends XmlAdapter<AdaptedCompany, Company> {
  public static class AdaptedCompany {
    @XmlAttribute
    String name;
    @XmlIDREF
    @XmlAttribute
    Person principal;
  }

  @Override
  public AdaptedCompany marshal(Company v) throws Exception {
    AdaptedCompany a = new AdaptedCompany();
    a.name = v.getName();
    a.principal = v.getPrincipal();
    return a;
  }

  @Override
  public Company unmarshal(AdaptedCompany v) throws Exception {
    return new Company(v.name, v.principal);
  }
}
4

0 回答 0