JAXB解组XML类强制转换exception

我正在使用这个JAXB Collection Generics解组我的字符串xml并返回List类型。 这是我使用的方法。

public static  List unmarshalCollection(Class cl, String s) throws JAXBException { return unmarshalCollection(cl, new StringReader(s)); } public static  List unmarshalCollection(Class cl, Reader r) throws JAXBException { return unmarshalCollection(cl, new StreamSource(r)); } private static  List unmarshalCollection(Class cl, Source s) throws JAXBException { JAXBContext ctx = JAXBContext.newInstance(JAXBCollection.class, cl); Unmarshaller u = ctx.createUnmarshaller(); JAXBCollection collection = u.unmarshal(s, JAXBCollection.class).getValue(); return collection.getItems(); } 

示例getter和setter:

  @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 = "FooBar
US
"; List p = unmarshalCollection(Person.class,xml); for(Person person : p ){ System.out.println(person); } }

抛出exception

 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) 

我做错了什么? 有什么想法吗?谢谢。

您的列表不是您期望的Person对象列表。 由于java的generics类型擦除,在尝试在循环中转换为person之前,您没有看到错误。

尝试:

 List 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