users@jaxb.java.net

Re: Customize java.lang.Object Bindings

From: Kohsuke Kawaguchi <Kohsuke.Kawaguchi_at_Sun.COM>
Date: Tue, 31 Jul 2007 09:12:03 -0700

Shelley wrote:
> My content tree contains an @XmlElement of type Object, which should be
> mapped to the XML type, anySimpleType.
>
> @XmlElement(required = true, nillable = true)
> protected Object value;
>
> During marshalling, if an unknown Java type object has been set (unknown per
> the "Default Data Type Bindings"), a MarshalException will be thrown. (ie:
> MarshalException "Caused by: javax.xml.bind.JAXBException: class <
> java.util.ArrayList> nor any of its super class is known to this context.")
>
> I would like to prevent this exception from occurring, and allow any Object
> type to be set and successfully marshalled/unmarshalled. If the type is not
> a default data type, the value should be converted to a String (either
> object.toString() or some custom logic to determine the appropriate String
> based on the class), and the XML type should be xs:anySimpleType.
>
> For example, for the following content tree:
> List<String> list = new ArrayList<String>(2);
> list.add("a");
> list.add("b");
> myXmlType.setValue(list);
> the XML output should be as follows:
> <value xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="
> http://www.w3.org/2001/XMLSchema" xsi:type="xs:anySimpleType">[a, b]</value>
>
> A possible solution would involve creation of a custom XmlJavaTypeAdapter to
> customize this binding, however, this would currently require a great deal
> of rework of the existing logic which parses through the known data types
> (ex: com.sun.xml.bind.v2.runtime.JAXBContextImpl.getBeanInfo()). The
> DatatypeConverter contains print and parse methods for anySimpleType, but
> these methods only use String parameters and return values (not Objects).
>
> Any suggestions on how to accomplish this customized binding between Object
> and anySimpleType would be appreciated. Thank you!

You'd have to write an adapter for sure, but I guess the question you
have really more like "how can I know if the given type is bindable by
JAXB already, so that I can decide whether I need to do toString() or not"?

And the answer is to use JAXBContextImpl.getBeanInfo(), as you found
out. I'm not sure what you mean by "great deal of rework", as it just
involves one method invocation. There's a legitimate concern for relying
on the implementation detail method, yes.

-- 
Kohsuke Kawaguchi
Sun Microsystems                   kohsuke.kawaguchi_at_sun.com