2010-11-22 58 views
7

有没有人设法从没有XJC的JAXB模式文件生成java代码?动态生成java源代码(没有xjc)

有点类似于

JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler() 

用于动态编译的飞行Java代码。

注:运行于JDK 6,这意味着com.sun.*工具软件包已经取消(用于提示感谢Blaise Doughan

回答

5

我必须包含一些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源将被放置在输出目录

1
+0

谢谢!我需要额外的软件包吗?我的JDK 6类路径中没有com.sun.tools.xjc。* com.sun.tools.xjc.api。*。 java -version:Java(TM)SE运行时环境(build 1.6.0_22-b04) – Osw 2010-11-22 17:46:40

+0

4.2。研究任何工具特定或com.sun。* API(JDK 6采用指南)。 http://www.oracle.com/technetwork/java/javase/adoptionguide-137484.html#4.2 – Osw 2010-11-22 18:01:44

1

获取JAXB参考实现here

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

3

该代码在特定目录生成的文件/封装结构:

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)); 

    } 
} 
0

得到Maven中的依赖关系的另一种方式;

<dependency> 
     <groupId>org.glassfish.jaxb</groupId> 
     <artifactId>jaxb-xjc</artifactId> 
     <version>2.2.11</version> 
    </dependency>