title: JAXB: Problem deserializing a class B that extends a class A
body: <p>Please consider the following example:</p>
  
  <p>There is a <strong>ClassA</strong> and a <strong>ClassB</strong> which extends it. My problem is now that I have to unmarshall a <strong>ClassB</strong> from an xml file. Please note that <strong>ClassA</strong> can not be changed as it is not under my control. </p>
  
  <p>Several problems are noted in this example:</p>
  
  <p>The main problem is that <strong>ClassA</strong> does not have a default no-arg constructor which is required by JAXB without Adapter. Therefore I implemented <strong>MyAdapter</strong> which maps <strong>ClassB</strong> to the simple class <strong>ValB</strong> which can be processed by JAXB without any problems. </p>
  
  <p>The main problem is how to make JAXB use this adapter? Neither defining the  <strong>@XmlJavaTypeAdapter</strong> on class level nor registering the Adapter to the unmarshaller does it.</p>
  
  <p>Does anybody know how to make JAXB use <strong>MyAdapter</strong> so that the unmarshaller returns an object that is an instance of <strong>ClassA</strong>?</p>
  
  <pre><code>public class JaxbTest {
  
      public static abstract class ClassA {
          public ClassA(String id) {
          }
      }
  
      @XmlRootElement
      @XmlJavaTypeAdapter(MyAdapter.class) // does not have an effect
      public static class ClassB extends ClassA {
  
          public String text;
  
          public ClassB() {
              super("");
          }
      }
  
      public static class ValB {
          public String text;
      }
  
      public static class MyAdapter extends XmlAdapter&lt;ValB, ClassB&gt; {
  
          @Override
          public ClassB unmarshal(ValB v) throws Exception {
              ClassB b = new ClassB();
              b.text = v.text;
              return b;
          }
  
          @Override
          public ValB marshal(ClassB v) throws Exception {
              ValB b = new ValB();
              b.text = v.text;
              return b;
          }
  
      }
  
      public static void main(String[] args) {
          try {
              JAXBContext context = JAXBContext.newInstance(ClassB.class);
              Unmarshaller unmarshaller = context.createUnmarshaller();
              unmarshaller.setAdapter(new MyAdapter()); // does not have an effect
              ClassA a = (ClassA) unmarshaller.unmarshal(new File("test.xml"));
              // do somthing with a
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
  }
  </code></pre>
  
  <p>BTW: Don't take the code too serious - it is just an example demonstrating the problem. I know that the definition of <strong>ClassA</strong> and <strong>ClassB</strong> are not really useful. </p>