2012-03-09 56 views
8

首先,我不是在談論Marshaller#Listener。 我正在談論那些class defined事件回調。JAXB應該從`beforeMarshal(Marshaller)`方法返回什麼?

有誰能告訴我應該從boolean beforeMarshal(Marshaller)方法返回什麼?

/** 
* Where is apidocs for this method? 
* What should I return for this? 
*/ 
boolean beforeMarshal(Marshaller marshaller); 

我的意思是,無論如何,使用轉換JPA's Long @Id to JAXB's String @XmlID與JAXB-RI沒有莫西此方法。

[編輯] a void版本似乎雖然工作。這只是一個文檔問題?

回答

7

簡答

boolean返回類型是一個文檔的錯誤。返回類型應爲void

長的答案

我的意思是,無論如何,使用轉換JPA的龍@Id到 JAXB的String此方法@XmlID

你可以使用EclipseLink JAXB (MOXy),因爲它不具備用@XmlID註解的字段/屬性的類型爲String

與JAXB-RI和沒有MOXy。

你可以使用一個XmlAdapter映射支持你的使用情況:

IDAdapter

XmlAdapterLong值轉換爲String值,以滿足@XmlID標註的要求。

package forum9629948; 

import javax.xml.bind.DatatypeConverter; 
import javax.xml.bind.annotation.adapters.XmlAdapter; 

public class IDAdapter extends XmlAdapter<String, Long> { 

    @Override 
    public Long unmarshal(String string) throws Exception { 
     return DatatypeConverter.parseLong(string); 
    } 

    @Override 
    public String marshal(Long value) throws Exception { 
     return DatatypeConverter.printLong(value); 
    } 

} 

@XmlJavaTypeAdapter註釋用於指定XmlAdapter

package forum9629948; 

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

@XmlAccessorType(XmlAccessType.FIELD) 
public class B { 

    @XmlAttribute 
    @XmlID 
    @XmlJavaTypeAdapter(IDAdapter.class) 
    private Long id; 

} 

package forum9629948; 

import javax.xml.bind.annotation.*; 

@XmlRootElement 
@XmlAccessorType(XmlAccessType.FIELD) 
public class A { 

    private B b; 
    private C c; 

} 

Ç

package forum9629948; 

import javax.xml.bind.annotation.*; 

@XmlAccessorType(XmlAccessType.FIELD)public class C { 

    @XmlAttribute 
    @XmlIDREF 
    private B b; 

} 

演示

package forum9629948; 

import java.io.File; 
import javax.xml.bind.*; 

public class Demo { 

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

     File xml = new File("src/forum9629948/input.xml"); 
     Unmarshaller unmarshaller = jc.createUnmarshaller(); 
     A a = (A) unmarshaller.unmarshal(xml); 

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

} 

輸入/輸出

<?xml version="1.0" encoding="UTF-8" standalone="yes"?> 
<a> 
    <b id="123"/> 
    <c b="123"/> 
</a> 
相關問題