考虑以下抽象类 -
public abstract class Car
{
public abstract void drive(double miles);
}
这是扩展上述类的示例类(用于说明目的)。
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
}
}
我有一个包含 Car 对象的报告类 -
@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; }
}
这是使用 JAXB 来编组 CarTestReport 对象的一段代码 -
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);
}
问题是,由于抽象类型 Car,JAXB 在编组 CarTestReport 对象时忽略它并且不编组 Ferrari 对象。我得到的输出是这个 -
<carTestReport>
<car/>
<date>July 6 2012</date>
<miles>200.0</miles>
</carTestReport>
如您所见,“汽车”节点下没有输入任何内容,即使已填充 Ferrari 对象。如何解决这个问题呢?