动态生成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; // 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中

此代码生成特定目录/包结构的文件:

 import java.io.File; import java.io.IOException; import org.xml.sax.InputSource; import com.sun.codemodel.JCodeModel; import com.sun.tools.xjc.api.S2JJAXBModel; import com.sun.tools.xjc.api.SchemaCompiler; import com.sun.tools.xjc.api.XJC; public class JAXCodeGen { public static void main(String[] args) throws IOException { String outputDirectory = "E:/HEAD/JAXB/src/"; // Setup schema compiler SchemaCompiler sc = XJC.createSchemaCompiler(); sc.forcePackageName("com.xyz.schema"); // Setup SAX InputSource File schemaFile = new File("Item.xsd"); InputSource is = new InputSource(schemaFile.toURI().toString()); // is.setSystemId(schemaFile.getAbsolutePath()); // Parse & build sc.parseSchema(is); S2JJAXBModel model = sc.bind(); JCodeModel jCodeModel = model.generateCode(null, null); jCodeModel.build(new File(outputDirectory)); } } 

以下可能会有所帮助:

  • JAXB Ant任务错误:xjc2 [ERROR] null未知位置

在此处获取JAXB参考实现。

它包括com.sun.tools.xjc.api.XJC类,允许您生成Java代码。

在Maven中获取依赖项的另一种方法;

   org.glassfish.jaxb jaxb-xjc 2.2.11