动态生成java源码(不带xjc) [英] Dynamically generate java sources (without xjc)

查看:33
本文介绍了动态生成java源码(不带xjc)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人设法在没有 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

这篇关于动态生成java源码(不带xjc)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆