Issue
I have a netbeans 8.1 platform application that contains two modules A and B. Both contain java classes that are being marshalled/unmarshalled to/from XML using JAXB.
A contains an abstract class which itself contains an interface:
@XmlAccessorType(value = XmlAccessType.FIELD)
abstract public class myAbstractClass {
public interface myInterface {
public void method();
}
}
B contains an extension of this abstract class and its member interface:
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;
}
}
}
I am trying to create a JAXBContext
in order to marshal an instance of B, as follows:
JAXBContext context = JAXBContext.newInstance("A.AbstractClassPackage", B.myExtendedClass.getClassLoader());
Where A.AbstractClassPackage is the package in which module A resides.
When I try and create the JAXBContext as described above, I get errors saying that I am trying to marshal an interface, and JAXB can't handle interfaces - like here:
My error actually refers to the interface myInterface, so I think that for some reason, JAXB is trying to create a context for myAbstractClass rather than myExtendedClass. I hunch that this is because the contextPath (argument 1 in the JAXBContext.newInstance
method) is incorrect.
I know that I can create a JAXB interface for derived classes when they reside in the same module, so my questions are:
Is it possible to create a JAXB context for derived classes where the abstract/interface class resides in a different netbeans module to the derived class?
If so, how do I set the contextPath to point to both modules?
Solution
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.
Answered By - user12066