0

我有一个 netbeans 8.1 平台应用程序,它包含两个模块 A 和 B。两者都包含使用 JAXB 编组/解组到 XML 的 java 类。

A 包含一个抽象类,该类本身包含一个接口:

@XmlAccessorType(value = XmlAccessType.FIELD)
abstract public class myAbstractClass {

    public interface myInterface {
        public void method();
    }

}

B 包含此抽象类及其成员接口的扩展:

import path.to.myAbstractClass;

@XmlAccessorType(value = XmlAccessType.FIELD)
@XmlRootElement(name = "mypackage-myextendedclass")
public class myExtendedClass extends myAbstractClass {

    public class mySubClass implements myInterface {

        @Override
        public void method()
        {
            // do some stuff
            return;
        }

    }

}

我正在尝试创建一个JAXBContext以编组 B 的实例,如下所示:

 JAXBContext context = JAXBContext.newInstance("A.AbstractClassPackage", B.myExtendedClass.getClassLoader());

其中 A.AbstractClassPackage 是模块 A 所在的包。

当我尝试如上所述创建 JAXBContext 时,我收到错误消息说我正在尝试编组接口,而 JAXB 无法处理接口 - 就像这里:

为什么 JAXB 说“xxx 是一个接口,而 JAXB 不能处理接口”。即使生成的类不是接口

我的错误实际上是指接口 myInterface,所以我认为出于某种原因,JAXB 试图为 myAbstractClass 而不是 myExtendedClass 创建上下文。我预感这是因为 contextPath(JAXBContext.newInstance方法中的参数 1)不正确。

我知道当派生类驻留在同一个模块中时,我可以为派生类创建一个 JAXB 接口,所以我的问题是:

  1. 是否可以为派生类创建 JAXB 上下文,其中抽象/接口类驻留在与派生类不同的 netbeans 模块中?

  2. 如果是这样,我如何将 contextPath 设置为指向两个模块?

4

1 回答 1

0

The solution turned out to be simple(ish), taken from the answer by Radim here: JAXB in Netbeans Module

I just needed to add a module dependency on JAXB API in module B (described in the original post). This is the netbeans JAXB class used at runtime, as opposed to the JDK version. If JAXB API is not included there are also errors looking like this (taken from the above link):

javax.xml.bind.JAXBException: ClassCastException: attempting to cast jar:file:/C:/Program%20Files/jmonkeyplatform/ide/modules/ext/jaxb/api/jaxb-api.jar!/javax/xml/bind/JAXBContext.class to jar:file:/C:/Program%20Files/Java/jdk1.6.0_21/jre/lib/rt.jar!/javax/xml/bind/JAXBContext.class.  Please make sure that you are specifying the proper ClassLoader.

The problem now makes sense (I think). By not including JAXB API, I was only using the non-runtime JDK version of JAXB, and my derived class - whose host module is loaded at runtime - was interpreted as the base class by JAXB, and the base class was not wholly JAXB compatible.

于 2016-02-11T08:54:22.860 回答