2014-02-06 2 views
0

JaxB를 사용하여 다음 작업을 수행하는 가장 좋은 방법을 찾고 있었지만 올바르게 작동하는 방법을 찾을 수 없습니다. 서브 클래스의 마샬링과 언 마샬링을 허용하기 위해 튜토리얼 here을 따라 갔다.JaxB 상속 마샬링 추상 클래스

하위 클래스가 제대로 마샬링되고 언 마샬링되도록하려면 @XmlRootElement 클래스에 래핑되어야한다는 점을 제외하고는 원하는 모든 것을 얻을 수 있습니다. 이것은 클래스 자체를 XML로 표현하는 것을 허용하지 않습니다.

는 그래서 같은 클래스를 갖고 싶어 :

import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; 

@XmlJavaTypeAdapter(ContactMethodAdapter.class) 
public abstract class ContactMethod { 

} 

public class Address extends ContactMethod {  

    protected String street;  
    protected String city; 

} 

public class PhoneNumber extends ContactMethod {  

    protected String number; 

} 

을하고 난 다음을 수행 할 수 있도록하려면 :

입력 :

<contact-method> 
    <street>Broadway</street> 
    <city>Seattle</city> 
</contact-method> 

홈페이지 :

public class Demo {  
    public static void main(String[] args) throws Exception {   
     ContactMethod meth = (ContactMethod) unmarshaller.unmarshal(xml); 

     if(ContactMethod instanceof Address){ 
     Address addr = (Address) meth; 

     addr.getStreet(); 

     // etc. 
     } 

     Address marshalAddr = new Address("Broadway", "Seattle");  

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

출력 :

<contact-method> 
    <street>Broadway</street> 
    <city>Seattle</city> 
</contact-method> 

이 방법을 수행하는 방법을 아는 사람이 있습니까?

+0

달성하려는 XML 표현은 무엇입니까? 어떤 요소가 존재하는지에 따라 엄격하게 하위 클래스를 결정하려고합니까? –

+0

기본적으로 전화 번호 나 주소를 루트로 마샬링하고 예제 에서처럼 목록에 래핑 할 필요없이 올바른 하위 클래스로 언 마샬 할 수있게하려고했습니다. 다른 질문을 읽은 후, "@XmlJavaTypeAdapter는 해당 클래스를 참조하는 필드/속성에만 적용되며 해당 클래스의 인스턴스가 XML 트리의 루트 객체가 아닌 경우"라고 말했습니다. 이렇게하면 XmlAdapter에 XmlRootElement로 주석을 추가하고 하위 클래스 변환을 직접 처리하는 것처럼 AdapterConactactMethod를 다른 클래스로 만들어야한다고 생각하게 만듭니다. –

답변

0

하나의 클래스 (AdaptedContactMethod)를 사용하여 추상 클래스를 모델링했습니다. 그런 다음 @XmlJavaTypeAdapter을 사용하는 대신 다른 하위 클래스에 마샬링 및 언 마샬링을 직접 처리했습니다.

이렇게하면 @XmlRootElement을 AdaptedContactMethod 구현에 넣을 수 있습니다. 목록에 넣지 않아도됩니다.