O'Reilly logo

Java SOA Cookbook by Eben Hewitt

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Generating a Schema from Java

Problem

You have a Java class and you want to generate an XML schema that matches it.

Solution

Run the command-line tool schemagen, which comes with Java SE 6. Alternatively, generate a schema at runtime with SchemaOutputResolver.

XML schemas can be generated from Java classes. You can use the annotations in the javax.xml.bind.annotations package to give the marshaler hints during the generation process. The schemagen utility comes with the reference implementation of JAXB, and so you can also find it among the Java SE 6 tools. Typing schemagen at the command line should give you usage information.

Using schemagen

In its simplest form, you can use schemagen by passing the name of the class you want to create a schema for. To invoke schemagen on Windows, you can use the batch file, and on Linux use the shell script. Here is the quickest example:

> schemagen Product.java

Note

You may run into problems using schemagen on Windows XP Service Pack 2 with JDK 1.6.0. This was filed as bug 6510966. Thanks to Brian Lee for discovering this.

This will first compile the specified Java class, and then write out a new XSD file called schema1.xsd in the current directory by default. To override the directory in which schemagen places its output, use the -d option. Finally, the Product class does not have any external dependencies, but if it did, you would need to specify those with the -cp option. Example 2-16 is what your Java source file looks like.

Example 2-16. Plain Product.java ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required