动态生成java源代码(不带xjc)

Osw*_*Osw 8 java schema dynamic jaxb

有没有人设法从没有XJC的JAXB模式文件生成Java代码?

有点类似

JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler()
Run Code Online (Sandbox Code Playgroud)

用于动态编译Java代码.

注意:在JDK 6上运行,意味着com.sun.*不推荐使用工具包(感谢Blaise Doughan的提示)

Osw*_*Osw 6

我必须为我的解决方案包含一些J2EE库才能工作,因为独立的JDK 6无法访问xjc实用程序类:

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));
Run Code Online (Sandbox Code Playgroud)

*.java源将放在outputDirectory中

  • 对于本地文件,我使用绝对路径并将系统ID设置为is.setSystemId(schemaFile.toURI()。toString())来解决。 (3认同)