如何使用Jaxb生成的ObjectFactory?
我正在使用Jaxb生成Java类。我的架构定义了以下元素:如何使用Jaxb生成的ObjectFactory?,jaxb,createinstance,objectfactory,Jaxb,Createinstance,Objectfactory,我正在使用Jaxb生成Java类。我的架构定义了以下元素: <xs:complexType name="AutomobileType" abstract="true"> <xs:sequence> <xs:element name="Color" type="core:ColorName"/> <xs:element name="Weight" type="core:PoundsWeightType"/>
<xs:complexType name="AutomobileType" abstract="true">
<xs:sequence>
<xs:element name="Color" type="core:ColorName"/>
<xs:element name="Weight" type="core:PoundsWeightType"/>
<xs:element name="Fuel" type="Fuel"/>
<xs:element name="NumDoors" type="xs:nonNegativeInteger"/>
<xs:element name="NumCylinders">
<xs:simpleType>
<xs:restriction base="xs:int">
<xs:minInclusive value="1"/>
<xs:maxInclusive value="12"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
</xs:sequence>
</xs:complexType>
<xs:element name="Automobile" type="AutomobileType"/>
但这不会编译,因为Automobile类是抽象的,因此我无法创建实例。还有另一种方法:
public AutomobileType createAutomobileType();
在JAXB中,xsd:complexType“AutomobileType”构造映射相同名称的类。它意味着与该XML模式类型等效的数据结构
JAXbeElement是一种(参数化)包装类型,它将java对象与元素名称和命名空间相关联,这就是为什么它的构造函数除了元素名称空间和元素名称之外,还将AutomobileType对象作为构造函数中的参数。
生成的ObjectFactory“createAutomobile(…)”只是包装该构造函数的一种方便方法,它从XML模式中硬编码名称空间和元素名称
虽然这个二分法一开始并不都是直截了当的,但考虑到你可以用另一个名称< /P>
它们在结构上是等价的,但元素名是不同的。您将拥有另一个ObjectFactory方法“createMotorcycle(…)”
为了构建xml元素的内容,可以创建一个未命名的automobileType对象,然后告诉JAXB它应该表示为哪个xml元素
关于这个主题,我无法推荐足够多的JAXB文档阅读。我的ObjectFactory只有一个方法。它没有无参数方法createAutomobileType()。这可能与complexType上的abstract=“true”有关。我打赌如果你把它设为false,你会得到它的。您是否定义了具体的子类型?如果是这样,您将在ObjectFactory中拥有相应的create方法,JAXB类型也将是抽象AutomobileType类的子类型,这意味着您可以将实例传递给CreateAutomobileType(AutomobileType)方法。JAXB非常紧密地映射了这两个结构的语义。我将Automobile类更改为非抽象类,现在一切都正常了。但是,当我尝试封送Automobile的实例时,会出现以下错误:无法将类型“com.cookmv.deregory.vehicles.schemas.AutomobileType”封送为元素,因为它缺少@XmlRootElement注释]
ObjectFactory objectFactory = new ObjectFactory();
objectFactory.createAutomobile(new Automobile());
public AutomobileType createAutomobileType();