【问题标题】:java.lang.InstantiationException while mapping abstract class using jaxb使用 jaxb 映射抽象类时出现 java.lang.InstantiationException
【发布时间】:2016-10-27 05:27:34
【问题描述】:

我正在关注博客文章: http://blog.bdoughan.com/2010/11/jaxb-and-inheritance-using-xsitype.html

我做了所有相同的事情,除了我的子类不是公共的并且与抽象类文件在同一个文件中。我得到 java.lang.InstantiationException 异常 javax.xml.bind.UnmarshalException:无法创建 org.apache.ambari.server.state.DependencyConditionInfo 的实例 - 有关联的例外: [java.lang.InstantiationException] 在 com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:647)

编辑

当我使用@XmlSeeAlso 时,我需要提供一个默认构造函数,因此我无法初始化子类的数据成员。

谁能帮我找到解决办法?谢谢

【问题讨论】:

    标签: inheritance jaxb xsitype


    【解决方案1】:

    为什么会失败是因为 Jaxb 将尝试创建 User 的实例。这是抽象的,因此是失败的。

    在你的抽象类上添加注释

    @XmlTransient //Prevents the mapping of a JavaBean property/type to XML representation
    @XmlSeeAlso({Admin.class, <other class>}) //Instructs JAXB to also bind other classes when binding this class
    

    查看每个的 javadoc(XmlTransient, XmlSeeAlso)

    这将阻止 jaxb 尝试初始化您的抽象类。

    我发现这种方法的唯一缺点是会在创建的 xml 中添加额外的命名空间信息。

    由@wyche5000 解决

    【讨论】:

    • 嗨 Luca,谢谢,添加 @XmlSeeAlso 后出现异常,但此标记需要子类的默认构造函数。如果我添加默认构造函数,我会得到一个 NullPointerException,因为子类的参数未初始化。可以指点一下吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    • 1970-01-01
    • 2015-03-22
    • 2020-07-07
    相关资源
    最近更新 更多