Наследование Jaxb с использованием замены, но не корневого элемента

Я просматривал блог Блейза http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-substitution.html для наследования Jaxb с использованием замены.

Я хочу реализовать то же самое, но не в корневом элементе. Я ищу этот тип XML в качестве вывода.

   <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <configuration>
      <customer>
        <address>
            <street>1 A Street</street>
        </address>
        <address>
            <street>2 B Street</street>
        </address>
        <phoneNumber>
            <mobileNo>xxx-xxx-xxxx</mobileNo>
         </phoneNumber>
     </customer>
 </configuration>

Ниже приведен файл Configuration.java.

    import javax.xml.bind.annotation.XmlRootElement;

    @XmlRootElement
     public class Configuration {

    private Customer customer;

    public Customer getCustomer() {
        return customer;
    }

     public void setCustomer(Customer customer) {
        this.customer = customer;
     }

    @Override
    public String toString() {
        return "\n Customer[ customer="+customer+"]";
     }

     }

Клиент.java

     public class Customer {
private List<ContactInfo> contactInfo;

@XmlElementRef
public List<ContactInfo> getContactInfo() {
    return contactInfo;
}

public void setContactInfo(List<ContactInfo> contactInfo) {
    this.contactInfo = contactInfo;
}

    }

Адрес.java

  public class Address extends ContactInfo {
private String street;

public String getStreet() {
    return street;
}

public void setStreet(String street) {
    this.street = street;
}

}

Номер телефона.java

    public class PhoneNumber extends ContactInfo{
private String mobileNo;

public String getMobileNo() {
    return mobileNo;
}

public void setMobileNo(String mobileNo) {
    this.mobileNo = mobileNo;
}

   }

Демо.java

     import java.util.ArrayList;
     import java.util.List;

     import javax.xml.bind.JAXBContext;
     import javax.xml.bind.Marshaller;

      public class Demo {
    public static void main(String[] args) throws Exception {
    Configuration configuration = new Configuration();
    Customer customer = new Customer();
    List<ContactInfo> contacts = new ArrayList<ContactInfo>();

    Address address = new Address();
    address.setStreet("1 A Street");
    contacts.add(address);

    Address address1 = new Address();
    address1.setStreet("2 B Street");
    contacts.add(address1);

    PhoneNumber phone = new PhoneNumber();
    phone.setMobileNo("408 431 8829");
    contacts.add(phone);

    customer.setContactInfo(contacts);

    configuration.setCustomer(customer);

    JAXBContext jc = JAXBContext.newInstance(Configuration.class);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
    marshaller.marshal(configuration, System.out);
    }
 }

В настоящее время я получаю следующее исключение

    Exception in thread "main" com.sun.xml.internal.bind.v2.runtime.IllegalAnnotationsException:     1 counts of IllegalAnnotationExceptions
    Invalid @XmlElementRef : Type "class Address" or any of its subclasses are not known to this context.

Может ли кто-нибудь помочь мне в этом?

Спасибо, Кватра.


person kwatra    schedule 21.06.2013    source источник


Ответы (1)


Проблема 1. Подклассы

Реализация JAXB (JSR-222) не может автоматическое обнаружение подклассов. Вы можете решить первое исключение, используя аннотацию @XmlSeeAlso в классе ContactInfo для ссылки на подклассы:

@XmlSeeAlso({Address.class, PhoneNumber.class})
public class ContactInfo {
}

Или вы можете ссылаться на них при создании файла JAXBContext.

 JAXBContext jc = JAXBContext.newInstance(Configuration.class, Address.class, PhoneNumber.class);

Проблема 2 – сопоставление

При использовании @XmlElementRef вам необходимо соединить его с @XmlRootElement. Если вы не хотите идти по этому пути, вы можете вместо этого использовать @XmlElements.

@XmlElements({
    @XmlElement(name="address", type=Address.class),
    @XmlElement(name="phoneNumber", type=PhoneNumber.class)
})
public List<ContactInfo> getContactInfo() {
    return contactInfo;
}
person bdoughan    schedule 21.06.2013
comment
Спасибо Блейз за быстрый ответ. Это работает как шарм. - person kwatra; 21.06.2013
comment
@XmlElementRef и @XmlRootElement у меня не работают, @XmlElements спас меня. - person Tony; 17.01.2017
comment
@XmlElements работал в моем случае, когда он был помещен в суперкласс. Я использую @XmlTransient в суперклассе вместе с XmlAlso. Подклассы используют @XmlType(propOrder). Каким-то образом @XmlTransient заставляет JAXB игнорировать объявление @XmlSeeAlso. - person Rohit V; 13.02.2019