Dynamically generate java sources (without xjc)

2019-01-14 09:23发布

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)

5条回答
贼婆χ
2楼-- · 2019-01-14 10:04

Another way of getting the dependencies in Maven;

    <dependency>
        <groupId>org.glassfish.jaxb</groupId>
        <artifactId>jaxb-xjc</artifactId>
        <version>2.2.11</version>
    </dependency>
查看更多
三岁会撩人
4楼-- · 2019-01-14 10:14

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

查看更多
放荡不羁爱自由
5楼-- · 2019-01-14 10:23

Get the JAXB reference implementation here.

It includes the com.sun.tools.xjc.api.XJC class that allows you to generate the Java code.

查看更多
太酷不给撩
6楼-- · 2019-01-14 10:24

This code generates files at specific Directories/Package structure:

import java.io.File;
import java.io.IOException;

import org.xml.sax.InputSource;

import com.sun.codemodel.JCodeModel;
import com.sun.tools.xjc.api.S2JJAXBModel;
import com.sun.tools.xjc.api.SchemaCompiler;
import com.sun.tools.xjc.api.XJC;

public class JAXCodeGen {
    public static void main(String[] args) throws IOException {

            String outputDirectory = "E:/HEAD/JAXB/src/";

            // Setup schema compiler
            SchemaCompiler sc = XJC.createSchemaCompiler();
            sc.forcePackageName("com.xyz.schema");

            // Setup SAX InputSource
            File schemaFile = new File("Item.xsd");
            InputSource is = new InputSource(schemaFile.toURI().toString());
          //  is.setSystemId(schemaFile.getAbsolutePath());

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

    }
}
查看更多
登录 后发表回答