tags:

views:

301

answers:

1

I'm trying to marshal an object that has an Object as one of its fields.

@XmlRootElement
public class TaskInstance implements Serializable {
   ...
   private Object dataObject;
   ...
}

The dataObject can be one of many different unknown types, so specifying each somewhere is not only impractical but impossible. When I try to marshal the object, it says the class is not known to the context.

MockProcessData mpd = new MockProcessData();
TaskInstance ti = new TaskInstance();
ti.setDataObject(mpd);

String ti_m = JAXBMarshall.marshall(ti);

"MockProcessData nor any of its super class is known to this context." is what I get.

Is there any way around this error?

+3  A: 

JAXB cannot marshal any old object, since it doesn't know how. For example, it wouldn't know what element name to use.

If you need to handle this sort of wildcard, the only solution is to wrap the objects in a JAXBElement object, which contains enough information for JAXB to marshal to XML.

Try something like:

QName elementName = new QName(...); // supply element name here
JAXBElement jaxbElement = new JAXBElement(elementName, mpd.getClass(), mpd);
ti.setDataObject(jaxbElement);
skaffman
Looks good, but I have two questions about this. Firstly, the element name - it's not exactly clear to me what it is used for, but I assume "dataObject" would be sufficient? And secondly, JAXBElement is a raw type, and the compiler warns me that it should be parametrized. I know a warning is a warning and not an error, but since I'm in unfamiliar territory, it seems like a good idea to find out more. I'm not sure what I'd parametrize it with either, since I'm dealing with 'Objects'. Thanks!
jcovert
@jcovert: The element name and namespace can be anything you like, so yes, `dataObject` would be fine. As for the generics, just use `JaxbElement<Object>`, it's just a compilation thing, JAXB doesn't care at runtime.
skaffman
@skaffman - It took me a few minutes to get it working, but indeed this is an excellent solution. One minor change (for anyone else who might encounter the same problem): `ti.setDataObject(jaxbElement)` should be `ti.setDataObject(jaxbElement.getValue())`Thanks again for the help!
jcovert