title: JAXB - marshall generic type (Date)
body: <p>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</p>
  
  <p>here is a piece of code I am talking about:</p>
  
  <pre><code>import javax.xml.bind.annotation.XmlRootElement;
  
  @XmlRootElement
  public class Entity&lt;T&gt; {
      private T field;
  
      public Entity() {
      }
  
      public T getField() {
          return field;
      }
  
      public void setField(T field) {
          this.field = field;
      }
  }
  </code></pre>
  
  <pre class="lang-java prettyprint-override"><code>import java.io.*;
  import java.util.Date;
  import javax.xml.bind.*;
  
  public class JaxbTest {
      public JaxbTest() {
  
          Entity&lt;Date&gt; ent = new Entity&lt;Date&gt;();
          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&lt;Date&gt; ent2 = (Entity&lt;Date&gt;) 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();
      }
  
  }
  </code></pre>
  
  <p>the above code throws exception:</p>
  
  <pre><code>java.lang.ClassCastException: com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl cannot be cast to java.util.Date
      at JaxbTest.&lt;init&gt;(JaxbTest.java:31)
      at JaxbTest.main(JaxbTest.java:38)
  </code></pre>
  
  <p>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</p>
  
  <p>thanks</p>