问题描述
有没有人设法在没有 XJC 的情况下从 JAXB 模式文件生成 java 代码?
Has anyone managed to generate java code from a JAXB schema file without XJC?
有点类似
JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler()
用于动态编译java代码.
used to dynamically compile java code on the fly.
注意:在 JDK 6 上运行,这意味着 com.sun.* 工具包已弃用(感谢 Blaise Doughan 提示)
Note: Running on JDK 6, meaning that com.sun.* tools packages are deprecated (thanks Blaise Doughan for the hint)
推荐答案
我必须包含一些 J2EE 库才能使我的解决方案正常工作,因为**的 JDK 6 无法访问 xjc 实用程序类:
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 源将被放置在 outputDirectory
*.java sources will be placed in outputDirectory