Invoke Javac At Runtime

You can access javac programmatically, that is compile Java source code at runtime from a running program! The javac compiler is made available via the tools.jar in the lib directory from the JDK. To get started with the following example you will need to add the tools.jar to your project’s classpath. You can find tools.jar in the lib directory of your JDK installation path.

One you have tools.jar in you classpath, you can create an instance of com.sun.tools.javac.Main, the entry point for javac.

[source:java]
com.sun.tools.javac.Main javac = new com.sun.tools.javac.Main();
[/source]

You can call the compile method on the javac instance passing in an array of strings as options. For example, here are the options that include the classpath and the output directory for the file to compile.

[source:java]
String[] options = new String[] {
“-classpath”, classpath, “-d”, outputDir, filename
};
[/source]

And of course you can use any of the other options such as -deprecation or -g. To compile a source file, just invoke compile as in the following code bit.

[source:java]
javac.compile(options);
[/source]

Compile Java this way can be helpful if your application generates one off statements that need to run in the system. I have used a mechanism like this to write what essentially is a script file but in Java code instead of Groovy or Jython. One thing to remember is that tools.jar is only available with the Java Development Kit, not the Java Runtime Environment.

Technorati Tags: , , , , , , , , ,