[英]how can i add binding.xml to Dynamically generated java sources (without xjc)
[英]Dynamically generate java sources (without 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参考实现。
它包括com.sun.tools.xjc.api.XJC类,允许您生成Java代码。
在Maven中获取依赖项的另一种方法;
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-xjc</artifactId>
<version>2.2.11</version>
</dependency>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.