How do I use the ObjectFactory generated by Jaxb?

I am using Jaxb to create Java classes. My schema has the following element:

<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"/>

      

As you can see, I have one item called Automobile.

Jaxb creates classes and ObjectFactory which I use to instantiate Automobile. What puzzles me is the Automobile instantiation method:

public JAXBElement<AutomobileType> createAutomobile(AutomobileType value)

      

Why does createAutomobile method have an argument? How to use this method?

I tried the following:

ObjectFactory objectFactory = new ObjectFactory();
objectFactory.createAutomobile(new Automobile());

      

but that won't compile because the Automobile class is abstract and therefore I cannot instantiate it.

+3


source to share


1 answer


There is another way:

 public AutomobileType createAutomobileType();

      

In JAXB, the xsd: complexType "AutomobileType" construct renders a class with the same name. It is for a data structure equivalent to an XML schema type.

JAXBElement <> is a (parameterized) wrapper type that associates a java object with an element name and namespace, and therefore its constructor takes an AutomobileType object as a parameter in the constructor, in addition to the element namespace and element name. The generated ObjectFactory "createAutomobile (..)" is just a convenient way to wrap this constructor, hard-code your namespace and element name from your XML schema.

While this dichotomy is not straightforward at first, consider that you could have another element with a different name



They would be structurally equivalent, but the element name would be different. You will have another ObjectFactory "createMotorcycle (...)" method.

You can create an unnamed carType object to create the content of the xml element and then tell JAXB exactly which XML element it should be rendered as.

I can't recommend enough to read the JAXB documentation on this topic.

+2


source







All Articles