Dynamically generate java sources (without xjc)(动态生成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)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:动态生成java源码(不带xjc)
基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- Struts2 URL 无法访问 2022-01-01
