>

Vaibhav's Blog Space

Compilation on Fly !

Wednesday Jun 04, 2008

Weeks back, I had a discussion with one of my colleagues on classLoader. Actually his classLoader is not able to perform certain job but then suddenly he asked me about any option in Java from which I can generate class file at runtime. Yes, why not. This is how JSP Compiler,Jasper works. There are some of the older way to do this in previous Java. But from J2SE 6 and onwards, one can do it neatly. 

J2SE 6 has added a package called javax.tools which has some awesome work to do. And the above task is one of it. We are going to use a class call ToolProvider which provides method to locate tools like Compiler :-).

Here I have written a simple code which go ahead and compile all the java files in a given directory at runtime and show the result.

import java.io.*;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class RuntimeCompilation {

    public static void main(String args[]) throws IOException {
        String dirName = "E:\\Program Files\\Java\\jdk1.6.0\\bin\\compiler";
        File f = new File(dirName);
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (f.isDirectory() == false) {
            System.out.println("Directory is not correct");
        } else {
            String lists[] = f.list();
            for (int i = 0; i < lists.length; i++) {
                if (lists[i].endsWith("java")) {
                    int results = compiler.run(null, null, null, lists[i]);
                    System.out.println("Compiling ..." + lists[i] + "      " + (results == 0));
                }
            }
        }
    }
}
 

I have 4-5 Java files at this location: E:\Program Files\Java\jdk1.6.0\bin\compiler. So, simply checked the directory and then list the file and pass it into the compilation process, thats it.Code is not written cleanly but do the basic job :). javax.tools package is quite amazing, have a look !

[0] Comments
Like this post? del.icio.us | furl | slashdot | technorati | digg