Search code examples
javafileclassxsdjcodemodel

Convert Java file (from JCodeModel) to Java class by code (instead of Javac etc.)


I do have the following code, that uses a XSD file to create a Java file. Now, I need to convert the Java file (from JCodeModel) to a Java class, that I can create/use in my project. Unfortunately, it is created during runtime, so I cannot add it to the project. It is important, that the solution is based on code. So, how do I convert a Java file to a Java class by code (instead of using Javac etc.)?

public static void xsdStructure() throws Exception
{
    String directory = "D:/PROJEKTE/";

    SchemaCompiler sc = XJC.createSchemaCompiler();
    sc.forcePackageName("de.monster.jaxb");

    File myXsd = new File("sql.xsd");
    InputSource source = new InputSource(myXsd.toURI().toString());

    sc.parseSchema(source);
    S2JJAXBModel model = sc.bind();
    JCodeModel jCodeModel = model.generateCode(null, null);
    jCodeModel.build(new File(directory));
}

The file generated with jCodeModel.build(new File(directory)); looks like this:

public class QUERY {

@XmlElement(name = "SELECT", required = true)
protected QUERY.SELECT select;
@XmlElement(name = "TABLE")
protected List<QUERY.TABLE> table;
@XmlElement(name = "JOIN")
protected List<QUERY.JOIN> join;
@XmlElement(name = "WHERE", required = true)
protected String where;
@XmlElement(name = "GROUP", required = true)
protected QUERY.GROUP group;
@XmlElement(name = "ORDER", required = true)
protected QUERY.ORDER order;
@XmlAttribute(name = "author")
protected String author;

public QUERY.SELECT getSELECT() {
    return select;
}

public void setSELECT(QUERY.SELECT value) {
    this.select = value;
}

public List<QUERY.TABLE> getTABLE() {
    if (table == null) {
        table = new ArrayList<QUERY.TABLE>();
    }
    return this.table;
}

public List<QUERY.JOIN> getJOIN() {
    if (join == null) {
        join = new ArrayList<QUERY.JOIN>();
    }
    return this.join;
}

public String getWHERE() {
    return where;
}

public void setWHERE(String value) {
    this.where = value;
}

public QUERY.GROUP getGROUP() {
    return group;
}

public void setGROUP(QUERY.GROUP value) {
    this.group = value;
}

public QUERY.ORDER getORDER() {
    return order;
}

public void setORDER(QUERY.ORDER value) {
    this.order = value;
}

public String getAuthor() {
    return author;
}

public void setAuthor(String value) {
    this.author = value;
}

...

Solution

  • StandardJavaFileManager

    Every compiler which implements this interface provides a standard file manager for operating on regular files. The StandardJavaFileManager interface defines additional methods for creating file objects from regular files.

    http://docs.oracle.com/javase/8/docs/api/javax/tools/JavaCompiler.html