Code Generation Using Jcodemodel

I am trying to create java code using jcodemodel in my maven project. My maven project has three modules. I wrote a jcodemodel sample in one of my modules for testing purposes. But when I execute it, it causes an error in the line. But I created a directory and also checked. I checked this example in a simple maven project, it works. But when I give it inside the maven module, it throws an error. where does it check the build file?

codeModel.build(new File("src/main/java/check"));

java.io.IOException: src \ main \ java \ check: nonexistent directory at com.sun.codemodel.writer.FileCodeWriter. (FileCodeWriter.java:73)

public class Consumer {

    /**
     * @param args
     * @throws JClassAlreadyExistsException 
     * @throws IOException 
     * @throws JAXBException 
     */
    public static void main(String[] args) throws JClassAlreadyExistsException, IOException, JAXBException {
            writeCodeModel("com.cts");
    }

    public static JType getTypeDetailsForCodeModel(JCodeModel jCodeModel, String type) {
        if (type.equals("Unsigned32")) {
            return jCodeModel.LONG;
        } else if (type.equals("Unsigned64")) {
            return jCodeModel.LONG;
        } else if (type.equals("Integer32")) {
            return jCodeModel.INT;
        } else if (type.equals("Integer64")) {
            return jCodeModel.LONG;
        } else if (type.equals("Enumerated")) {
            return jCodeModel.INT;
        } else if (type.equals("Float32")) {
            return jCodeModel.FLOAT;
        } else if (type.equals("Float64")) {
            return jCodeModel.DOUBLE;
        } else {
            return null;
        }
    }

    // Function to generate CodeModel Class
    public static void writeCodeModel(String factroyPackage) throws JAXBException {
        try {

            JCodeModel codeModel = new JCodeModel();
            JDefinedClass foo = codeModel._class( "Foo" ); //Creates a new class

            JMethod method = foo.method( JMod.PUBLIC, Void.TYPE, "doFoo" ); //Adds a method to the class
            method.body()._return( JExpr.lit( 42 ) ); //the return statement

            codeModel.build(new File("src/main/java/check"));

        } catch (Exception ex) {

            ex.printStackTrace();
        }
    }

}
+3
source share
1 answer

The exception message seems pretty clear:

java.io.IOException: src\main\java\check: com.sun.codemodel.writer.FileCodeWriter. (FileCodeWriter.java:73)

, , , target/generated-sources/.

File target = new File("target/generated-sources/java");
if (!target.mkdirs()) {
    throw new IOException("could not create directory");
}
codeModel.build(target);
+3

All Articles