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 process of compiling can be start by obtaining a JavaCompiler
from the ToolProvider.getSystemJavaCompiler()
.
The simplest way to compile is by calling the run()
method of the compiler 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.
When error happened during compilation process the non-zero result code will be returned. After the compile process you’ll have the Hello.class
just as if you were compiling using the javac
command.
package org.kodejava.tools;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
public class CompileHello {
public static void main(String[] args) {
System.out.println(System.getProperty("user.dir"));
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int result = compiler.run(null, null, null,
"kodejava-tools/src/main/java/org/kodejava/tools/Hello.java");
System.out.println("Compile result code = " + result);
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024