Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 com.sun.* tools packages are deprecated (thanks Blaise Doughan for the hint)

like image 787
andbi Avatar asked Nov 22 '10 17:11

andbi


1 Answers

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();
sc.forcePackageName("com.xyz.schema.generated");

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

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

*.java sources will be placed in outputDirectory

like image 151
andbi Avatar answered Oct 07 '22 20:10

andbi