title: How to make JAXB Marshaller marshal abstract class based on its runtime type?
body: <p>Consider the following abstract class -</p>
  
  <pre><code>public abstract class Car
  {
      public abstract void drive(double miles);
  }
  </code></pre>
  
  <p>Here's a sample class (for illustration purposes) that extends the above class.</p>
  
  <pre><code>public class Ferrari extends Car
  {
      private String lastUsed; // Ferrari specific field not in Car
      private boolean f1Car;   // Ferrari specific field not in Car
  
      @XmlElement
      public void setF1Car(boolean f1Car)
      {
          this.f1Car = f1Car;
      }
  
      public boolean isF1Car() { return f1Car; }
  
      @XmlElement
      public void setLastUsed(String lastUsed)
      {
          this.lastUsed = lastUsed;
      }
  
      public String getLastUsed() { return lastUsed; }
  
      public void drive(double miles)
      {
          // implementation
      }
  }
  </code></pre>
  
  <p>I have a report class that contains a Car object - </p>
  
  <pre><code>@XmlRootElement
  public class CarTestReport
  {
      private String date;
      private double miles;
      private Car car;
  
      @XmlElement
      public void setDate(String date) { this.date = date;}
  
      public String getDate() {return date;}
  
      @XmlElement
      public void setMiles(double miles) { this.miles = miles; }
  
      public double getMiles() {return miles;}
  
      @XmlElement
      public void setCar(Car car) { this.car = car; }
  
      public Car getCar() { return car; }
  }
  </code></pre>
  
  <p>And here is the piece of code using JAXB to Marshall a CarTestReport object - </p>
  
  <pre><code>public static void main(String[] args) throws Exception
  {
      Ferrari ferrari = new Ferrari();
      ferrari.setLastUsed("July 5 2012");
      ferrari.setF1Car(false);
  
      CarTestReport  report = new CarTestReport();
      report.setDate("July 6 2012");
      report.setMiles(200);
      report.setCar(ferrari);
  
      File file = new File("carTestReport.xml");
      JAXBContext jaxbContext = JAXBContext.newInstance(CarTestReport.class);
      Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
  
      jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
      jaxbMarshaller.marshal(report, file);
  }
  </code></pre>
  
  <p>The problem is, because of the abstract type Car, JAXB ignores it and doesn't marshall the Ferrari object when it marshals the CarTestReport object. The output I get is this - </p>
  
  <pre><code>&lt;carTestReport&gt;
    &lt;car/&gt;
    &lt;date&gt;July 6 2012&lt;/date&gt;
    &lt;miles&gt;200.0&lt;/miles&gt;
  &lt;/carTestReport&gt; 
  </code></pre>
  
  <p>As you can see, nothing was entered under the 'car' node, even though the Ferrari object was populated. How to solve this problem?</p>