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

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

问题描述

有没有人设法从没有XJC的JAXB架构文件生成java代码?



有点类似于

  JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler() 

用于动态编译java代码。



注意:在JDK 6上运行,意味着 com.sun。* 工具包已被弃用(感谢 Blaise Doughan 的提示)

解决方案

我不得不为我的解决方案包含一些J2EE库,因为独立的JDK 6不提供对xjc实用程序类的访问:

  import 。com.sun.codemodel *; 
import com.sun.tools.xjc.api。*;
import org.xml.sax.InputSource;

//配置源&输出
String schemaPath =path / to / schema.xsd;
String outputDirectory =schema / output / source /;

//安装架构编译器
SchemaCompiler sc = XJC.createSchemaCompiler();
sc.forcePackageName(com.xyz.schema.generated);

//设置SAX InputSource
文件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


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)

解决方案

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

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

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