Osw Osw - 1 year ago 113
Java Question

Dynamically generate java sources (without xjc)

Has anyone managed to generate java code from a JAXB schema file without XJC?

Somewhat similar to

JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler()

used to dynamically compile java code on the fly.

Note: Running on JDK 6, meaning that
tools packages are deprecated (thanks Blaise Doughan for the hint)

Osw Osw
Answer Source

I had to include some J2EE libraries for my solution to work cause standalone JDK 6 provides no access to xjc utility classes:

import com.sun.codemodel.*;
import com.sun.tools.xjc.api.*;
import org.xml.sax.InputSource;

// Configure sources & output
String schemaPath = "path/to/schema.xsd";
String outputDirectory = "schema/output/source/";

// Setup schema compiler
SchemaCompiler sc = XJC.createSchemaCompiler();

// Setup SAX InputSource
File schemaFile = new File(schemaPath);
InputSource is = new InputSource(new FileInputStream(schemaFile));

// Parse & build
S2JJAXBModel model = sc.bind();
JCodeModel jCodeModel = model.generateCode(null, null);
jCodeModel.build(new File(outputDirectory));

*.java sources will be placed in outputDirectory

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download