Java 解组NullPointerException(使用JAXB参考实现)

Java 解组NullPointerException(使用JAXB参考实现),java,xml,nullpointerexception,jaxb,Java,Xml,Nullpointerexception,Jaxb,我试图解压xml文件,但从JAXB库的深处得到了非常奇怪的NPE。你能帮我解决这个问题吗 以下是stacktrace的顶部: java.lang.NullPointerException at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:258) at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.handleGenericException(Lo

我试图解压xml文件,但从JAXB库的深处得到了非常奇怪的NPE。你能帮我解决这个问题吗

以下是stacktrace的顶部:

java.lang.NullPointerException
at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:258)
at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.handleGenericException(Loader.java:245)
at com.sun.xml.bind.v2.runtime.unmarshaller.Scope.add(Scope.java:123)
at com.sun.xml.bind.v2.runtime.property.ArrayERProperty$ReceiverImpl.receive(ArrayERProperty.java:213)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.endElement(UnmarshallingContext.java:538)
以下是xml类代码:

public class Base {
    public Base() {
    }
}

public class A  extends Base {
    public A() {
    }
}

public class B extends Base{
    public B() {
    }
}


@XmlRootElement(name = "test")
@XmlAccessorType
public class TestXml {
    @XmlElementWrapper(name = "list")
    @XmlAnyElement
    @XmlJavaTypeAdapter(Adapter.class)
    public List<Base> list = new ArrayList<>();
}
最后,这里是xml文件,我尝试对其进行解组:

<test>
    <list>
        <item class="my.package.A" />
        <item class="my.package.B" />
    </list>
</test>
导致NPE。当我删除这行代码并将unmarshall()的return语句替换为

return new A(); //for example

没有NPE发生。

尝试更改此行

// 1. Determine the values type from the type attribute.
    Class<?> clazz = classLoader.loadClass(element.getAttribute("class"));
//1。从类型属性确定值类型。
Class clazz=classLoader.loadClass(element.getAttribute(“类”);
对,

//1。从类型属性确定值类型。
Class clazz=ClassLoader.loadClass(element.getAttribute(“类”);

clazz变量为空的原因。

在另一个解组过程中,我尝试处理一个解组过程时,有完全相同的堆栈跟踪

基本上,在adapater的“unmarshal”方法中,我通过剥离其值并仅保留其属性来构建一个假“标记”。然后,为了正确地提取属性,我使用了jaxb解组


jaxb中的错误非常严重,我真的没有在代码中看到任何错误。我通过迁移到最新和最好的jaxb核心库(从2.2.6迁移到2.2.11)修复了我的问题。

这是JDK1.7附带的jaxb版本(2.2.4-2)中的一个bug


对我来说,在类路径中包括最新版本的JAXB(2.2.11)解决了这个问题。

Aditya,类加载器类没有静态方法loadClass:-(我使用Java 7。只需检查您是否正在使用Java.lang.ClassLoader,因为Java 7中的ClassLoader有loadClass方法。检查此链接,是的,它有,但此方法不是静态的。您可以使用Class.forName或参考此答案使用loadClass方法加载您的类,ClassLoader找到类,因此clazz变量不是空的。是的,我得到了这个答案。)类加载器:classloader=Thread.currentThread().getContextClassLoader();
JAXBElement jaxbElement = unmarshaller.unmarshal(source, clazz);
return new A(); //for example
// 1. Determine the values type from the type attribute.
    Class<?> clazz = classLoader.loadClass(element.getAttribute("class"));
// 1. Determine the values type from the type attribute.
    Class<?> clazz = ClassLoader.loadClass(element.getAttribute("class"));