In many Java applications, you need to invoke the Java compiler in your program to compile and run. However, in earlier versions (Java SE5 and previous versions) only the Java compiler could be invoked through the Com.sun.tools.javac package in Tools.jar, but since Tools.jar is not a standard Java library, the path to the jar must be set when used. The Java SE6 provides us with a standard package to manipulate the Java compiler, which is the Javax.tools package. Using this package, we can not add the jar file path to the classpath.
First, use the Javacompiler interface to compile Java source program
There are many ways to use the Java API to compile Java source programs, now let's look at one of the easiest ways to compile with Javacompiler.
We can get an instance of a Javacompiler interface by Toolprovider The static method of the class Getsystemjavacompiler.
Javacompiler compiler = Toolprovider.getsystemjavacompiler ();
The most central method of Javacompiler is run. This method enables you to compile Java source programs. This method has 3 fixed parameters and a variable parameter (the variable parameter is a new parameter type provided from Jave SE5, which is represented by type ... argu). The first 3 parameters are used to provide parameters for the Java compiler, to obtain output information from the Java compiler, and to receive compiler error messages, and subsequent variable parameters can pass in one or more Java source program files. Returns 0 if the run compilation succeeds.
int run (InputStream in, outputstream out, OutputStream err, String ... arguments)
If the first 3 arguments pass in null, then the Run method replaces the standard input, output, system.in, System.out, and System.err. If we are compiling a Test.java file and will use standard input and output, run uses the following methods:
int results = Tool.run (NULL, NULL, NULL, "Test.java");
Here's the complete code using Javacompiler:
import java.io.*;
import javax.tools.*;
public class test_compilerapi
{
public static void main(String args[]) throws IOException
{
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int results = compiler.run(null, null, null, "test.java");
System.out.println((results == 0)?"编译成功":"编译失败");
// 在程序中运行test
Runtime run = Runtime.getRuntime();
Process p = run.exec("java test");
BufferedInputStream in = new BufferedInputStream(p.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String s;
while ((s = br.readLine()) != null)
System.out.println(s);
}
}
public class test
{
public static void main(String[] args) throws Exception
{
System.out.println("JavaCompiler测试成功!");
}
}
Compilation Successful output results:
Compilation successful
Javacompiler Test Successful
Output result of compilation failure:
符号: 方法 printlnln(java.lang.String)
位置: 类 java.io.PrintStream
System.out.printlnln("JavaCompiler测试成功!");
^
1 错误
编译失败
Test.java:9: Symbol not found