The Java EE 5 Tutorial

XmlType Example

The XmlType example demonstrates the use of the @XmlType annotation. The @XmlType annotation maps a class or an enum type to a XML Schema type.

A class must have either a public zero-argument constructor or a static zero-argument factory method in order to be mapped by this annotation. One of these methods is used during unmarshalling to create an instance of the class. The factory method may reside within in a factory class or the existing class.

There is an order of precedence as to which method is used for unmarshalling:

In this example, a factory class provides zero arg factory methods for several classes. The @XmlType annotation on class OrderContext references the factory class. The unmarshaller will use the identified factory method in this class.

public class OrderFormsFactory {
    public OrderContext newOrderInstance() {
        return new OrderContext()
    }
    public PurchaseOrderType newPurchaseOrderType() {
        return new newPurchaseOrderType();
    }
}
@XmlType(name="oContext", factoryClass="OrderFormsFactory",
  factoryMethod="newOrderInstance")
public class OrderContext {
    public OrderContext(){ ..... }
}

In this example, a factory method is defined in a class, which also contains a standard class construct. Because the factoryMethod value is defined and no factoryClass is defined, the factory method newOrderInstance is used during unmarshalling.

@XmlType(name="oContext", factoryMethod="newOrderInstance")
 public class OrderContext {
    public OrderContext(){ ..... }
    public OrderContext newOrderInstance() {
         return new OrderContext();
    }
}

Building and Running the XmlType Example Using NetBeans IDE

Follow these instructions to build and run the XmlType example on your Application Server instance using the NetBeans IDE.

  1. In NetBeans IDE, select File->Open Project.

  2. In the Open Project dialog, navigate to tut-install/javaeetutorial5/examples/jaxb/.

  3. Select the j2s-xmlType folder.

  4. Select the Open as Main Project check box.

  5. Click Open Project.

  6. Right-click the j2s-xmlType project and select Run.

Building and Running the XmlType Example Using Ant

To compile and run the XmlType example using Ant, in a terminal window, go to the tut-install/javaeetutorial5/examples/jaxb/j2s-xmlType/ directory and type the following:


ant runapp