Search code examples
javacode-generationjava-compiler-api

Compiling generated code and jar with JavaCompiler


I have generated code that can be compiled on commandline with javac compiler like this:

javac generated/Buffer.java -classpath framework-core.jar

Now I am trying to automate the compiling in tests with JavaCompiler. With the following code (from http://docs.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html):

String path = "/generated/Buffer.java";
File file = new File(System.getProperty("user.dir") + path);
File[] files1 = new File[]{file};
//HERE I WOULD LIKE TO GIVE framework-core.jar TO COMPILER

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(Arrays.asList(files1));

compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();

fileManager.close();

I am able to produce same errors I get from the command line, if I do not provide classpath to framework-core.jar. How could I give classpath to that jar when working with programmatical JavaCompiler?

I also wonder if there would be more straightforwarded ways to compile and run generated code.


Solution

  • Try to specify classpath option on your java compiler:

    List<String> optionList = new ArrayList<String>();
    // set compiler's classpath to the path of your framework-core.jar
    optionList.addAll(Arrays.asList("classpath","/lib/framework-core.jar"));
    ...
    compiler.getTask(null, fileManager, null, optionList, null, compilationUnits1).call();