I am having trouble to marshall/unmarshall generic type using JAXB. Everything works fine, but when my generic field is Date (java.util.Date), unmarshalling will produce XMLGregorianCalendar instead
here is a piece of code I am talking about:
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Entity<T> {
private T field;
public Entity() {
}
public T getField() {
return field;
}
public void setField(T field) {
this.field = field;
}
}
import java.io.*;
import java.util.Date;
import javax.xml.bind.*;
public class JaxbTest {
public JaxbTest() {
Entity<Date> ent = new Entity<Date>();
ent.setField(new Date());
StringWriter sw = new StringWriter();
try {
// marshall
JAXBContext jaxbContext = JAXBContext.newInstance(Entity.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(ent, sw);
// unmarshall
JAXBContext jc = JAXBContext.newInstance(Entity.class);
Unmarshaller u = jc.createUnmarshaller();
Entity<Date> ent2 = (Entity<Date>) u.unmarshal(new StringReader(sw
.toString()));// exception is thrown here
System.out.println(ent2.getField());
} catch (JAXBException e11) {
e11.printStackTrace();
}
}
public static void main(String[] args) {
new JaxbTest();
}
}
the above code throws exception:
java.lang.ClassCastException: com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl cannot be cast to java.util.Date
at JaxbTest.<init>(JaxbTest.java:31)
at JaxbTest.main(JaxbTest.java:38)
Could you help me how to fix it? I was thinking about some adapter that would be "active" only if field is Date, but I don't think it is possible
thanks
ent2.getField()
?