java.lang.ClassCastException:com.kk.COUNTRY无法强制转换为javax.xml.bind.JAXBElement

时间:2013-06-27 07:00:06

标签: java jaxb classcastexception unmarshalling

我的主要课程是

    public static void main(String[] args) throws JAXBException,
        FileNotFoundException {

    Class[] classes = new Class[5];
    classes[0] = com.kk.AddressDetails.class;
    classes[1] = com.kk.COUNTRY.class;
    classes[2] = com.kk.ObjectFactory.class;
    classes[3] = com.kk.Details.class;
    classes[4] = com.kk.Districts.class;

    JAXBContext context = JAXBContext.newInstance(classes);

    Unmarshaller unmarshaller = context.createUnmarshaller();

    JAXBElement<COUNTRY> unmarshal = (JAXBElement<COUNTRY>) unmarshaller
            .unmarshal(new File("src\\countrydetails.xml"));
    COUNTRY value = unmarshal.getValue();
            System.out.println(value);

因此,在编译时,我在线程“main”java.lang.ClassCastException中得到了此异常:com.kk.COUNTRY无法强制转换为javax.xml.bind.JAXBElement     在main.kk.ClientApp.main(ClientApp.java:31)

3 个答案:

答案 0 :(得分:3)

由于您的COUNTRY类使用@XmlRootElement注释,这意味着它与根元素唯一关联,而解组操作的结果将为COUNTRY

COUNTRY c = (COUNTRY) unmarshaller.unmarshal(xml);

如果COUNTRY有一个或多个相应的@XmlElementDecl注释,或者您使用的unmarshal方法采用Class参数,则会获得JAXBElement的实例}

JAXBElement<COUNTRY> c = unmarshaller.unmarshal(xml, COUNTRY.class);

了解更多信息

答案 1 :(得分:2)

那是因为Unmarshaller.unmarshal(File f)会返回Object而非JAXBElement

这是签名:

public Object unmarshal( java.io.File f ) throws JAXBException;

您的解决方案应该是:

COUNTRY value = unmarshaller.unmarshal(new StreamSource(new File("src\\countrydetails.xml")), COUNTRY.class);

答案 2 :(得分:0)

您不需要将unmarshl结果强制转换为JAXBElement,它应该只是您尝试解组的COUNTRY类。假设您已正确注释COUTNRY类,那么您可以简单地执行此操作:

COUNTRY unmarshal = (COUNTRY) unmarshaller
            .unmarshal(new File("src\\countrydetails.xml"));

按照本教程通过简单示例了解JAXB编组和解组:

http://www.mkyong.com/java/jaxb-hello-world-example/