本文介紹了JAXB 解組 XML 類強制轉換異常的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我正在使用這個 JAXB Collection Generics 來解組我的字符串 xml 并返回 List 類型.這是我使用的方法.
I'm using this JAXB Collection Generics to unmarshall my string xml and return the List type. Here's the methods I used.
public static <T> List<T> unmarshalCollection(Class<T> cl, String s)
throws JAXBException {
return unmarshalCollection(cl, new StringReader(s));
}
public static <T> List<T> unmarshalCollection(Class<T> cl, Reader r)
throws JAXBException {
return unmarshalCollection(cl, new StreamSource(r));
}
private static <T> List<T> unmarshalCollection(Class<T> cl, Source s)
throws JAXBException {
JAXBContext ctx = JAXBContext.newInstance(JAXBCollection.class, cl);
Unmarshaller u = ctx.createUnmarshaller();
JAXBCollection<T> collection = u.unmarshal(s, JAXBCollection.class).getValue();
return collection.getItems();
}
getter 和 setter 示例:
Example getters and setters:
@XmlRootElement(name = "person")
class Person{
private String firstName;
private String lastName;
private String address;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Person [firstName ="+firstName+" , lastName = "+lastName+" , address = "+address+"]";
}
}
主類:
public static void main(String[] args) throws JAXBException {
String xml = "<?xml version="1.0" encoding="UTF-8"?><person><firstName>Foo</firstName><lastName>Bar</lastName><address>U.S</address></person>";
List<Person> p = unmarshalCollection(Person.class,xml);
for(Person person : p ){
System.out.println(person);
}
}
拋出異常
Exception in thread "main" java.lang.ClassCastException: org.apache.xerces.dom.ElementNSImpl cannot be cast to com.Person
at com.JAXBUtil.main(JAXBUtil.java:62)
我做錯了什么?有什么想法嗎?謝謝.
What did I do wrong? Any ideas?Thanks.
推薦答案
您的列表不是您期望的 Person 對象列表.由于 java 的泛型類型擦除,在您嘗試在循環中強制轉換為 person 之前,您不會看到錯誤.
Your list is not a list of Person objects as you expect. Due to java's generic type erasure, you're not seeing the error until you try to cast to person in the loop.
試試:
List<Person> p = unmarshalCollection(Person.class,xml);
for(Object person : p ){
System.out.println(person.getClass());
}
參見 http://en.wikipedia.org/wiki/Generics_in_Java#Problems_with_type_erasure
這篇關于JAXB 解組 XML 類強制轉換異常的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!