有幾件事情要檢查:
- 是您
JAXBContext
意識到B
類的?您可以包括在用於創建JAXBContext
的類中,或者在A
類中添加@XmlSeeAlso({B.class})
。
- 是與
B
類B
對應的類型的名稱?默認爲b
。您可以使用@XmlType
註釋來指定名稱。
甲
package forum13712986;
import javax.xml.bind.annotation.XmlSeeAlso;
@XmlSeeAlso({B.class})
public class A {
}
乙
package forum13712986;
import javax.xml.bind.annotation.XmlType;
@XmlType(name="B") // Default name is "b"
public class B extends A {
}
演示
package forum13712986;
import java.io.StringReader;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(A.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
String xml = "<A xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:type='B'/>";
StreamSource source = new StreamSource(new StringReader(xml));
JAXBElement<A> jaxbElement = unmarshaller.unmarshal(source, A.class);
System.out.println(jaxbElement.getValue().getClass());
}
}
輸出
class forum13712986.B