Monday, July 4, 2011

How to compile a java source file from another Java source at runtime?

One of the cool features available in Java 6.0 (Mustang) is the ‘Java Compiler API’ which can be used compile a Java source file from another java file at run time.

Suppose we have the following class kept at C: drive of your disk:

public class FileToCompile {
public void sampleMethod() {
System.out.println("Method Called from FileToCompile");
}
}


Following code shows how can we compile this class at runtime:

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;

public class RuntimeCompilation {

public static void main(String[] args) {
String lsFileToCompile = "C:/FileToCompile.java";
// ToolProvider provides methods for locating javac, javah etc.
JavaCompiler loCompiler = ToolProvider.getSystemJavaCompiler();
int liResult = loCompiler.run(null, null, null, lsFileToCompile);
if (liResult == 0) {
System.out.println("Compilation Successful");
} else {
System.out.println("Compilation Failed");
}
}
}


Read the javadoc for JavaCompiler class for more information.

No comments: