Java Program to Compile a Java Class or File Programmatically using JavaCompiler Tool.
This example using the Java Compiler API introduced in JDK 1.6 to programmatically compile a Java class. Here we’ll compile the Hello.java.
The simplest way to compile is by calling the run() method of the JavaCompiler and passing the first three arguments with null value. These three argument will use the default System.in, System.out and System.err. The final parameter is the file of the Java class to be compiled.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import javax.tools.JavaCompiler; import javax.tools.ToolProvider; public class CompileHello { public static void main(String[] args) { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); int result = compiler.run(null, null, null, "src/org/javac/example/tools/Hello.java"); System.out.println("Compile result code = " + result); } } |