Saturday, 12 May 2012

How to Use the JavaCompiler.CompilationTask

There might be times when you have to generate Java source code programmatically. Fortunately, you do not have to resort to spawning a new process that runs the javac command. You can, instead, compile the code directly from inside your Java program.

So, let us write a class that contains a method that accepts a file-name as an argument, and compiles that file. We will primarily be making use of the classes in javax.tools package.

Here is the code for it,
package com.whycouch.toolstest;

import java.io.IOException;
import java.util.Locale;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

public class Compiler {
    JavaCompiler compiler;
    StandardJavaFileManager fileManager;

    Compiler(){
        compiler=ToolProvider.getSystemJavaCompiler();
        fileManager=compiler.getStandardFileManager(null, 
                                                    Locale.FRENCH, 
                                                    null);        
    }

    void compile(String file) throws IOException{
        Iterable<? extends JavaFileObject> files = 
                                 fileManager.getJavaFileObjects(file);
            //The compiler can compile one or more files, 
            //and takes the Iterable above as an argument
        JavaCompiler.CompilationTask task=compiler.getTask(null, 
                                                           fileManager, 
                                                           null, 
                                                           null,
                                                           null, 
                                                           files);        
        task.call(); // This actually does the compilation
    }

    public static void main(String[] args) throws IOException{
        Compiler c=new Compiler();
        c.compile("/tmp/T.java");
        System.out.println("DONE");
    }
}
If the file you pass to it compiles successfully, we will see no output, except from the System.out.println that we call after the compilation. If the file does not compile, the compilation errors show up in the same way that they are shown when we call the javac command.

No comments:

Post a Comment