这是用jaxb绑定一个xml文件所出现的异常:
Exception in thread "main" java.lang.ClassCastException: javax.xml.bind.JAXBElement cannot be cast to com.part.jaxp.Users
at com.part.jaxp.JavaTest.main(JavaTest.java:15)
package com.part.jaxp;
import java.io.File;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class JavaTest {
public static void main(String[] args) throws JAXBException {
JAXBContext jc = JAXBContext.newInstance("com.part.jaxp");
Unmarshaller unmarshaller = jc.createUnmarshaller();
Users users= (Users)unmarshaller.unmarshal(new File( "src/user.xml"));
//Books books = collection.getBooks();
List<User> userList = users.getUser();
for (User user : userList) {
System.out.println(user.getName());
}
}
}
------最佳解决方案--------------------
Users users= (Users)unmarshaller.unmarshal(new File( "src/user.xml"));
改成下面试试
Users users = (Users)((JAXBElement) unmarshaller.unmarshal(new File("src/user.xml"))).getValue();
------其他解决方案--------------------
有没有导入类
javax.xml.bind.JAXBElement
另外,看你环境里,编译、运行时用JDK版本一致不
------其他解决方案--------------------
这种方法还是不行!它会报这个错:Description Resource Path Location Type
JAXBElement cannot be resolved to a type JavaTest.java /eee/src/com/part/jaxp line 15 Java Problem
------其他解决方案--------------------
嗯 !谢了!已经解决了!