2010-11-22 61 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>