编译Java程序:
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import com.sun.tools.javac.Main;
public class Test {
public static void main(String[] argv) throws FileNotFoundException {
PrintWriter writer = new PrintWriter("result.txt");
String[] options = { "/Users/Biao/Desktop/FilteredJList.java" };
Main.compile(options, writer);
}
}
执行Java程序:
// Process proc = Runtime.getRuntime().exec(String.format("java %s", "FilteredJList"));
private void run(String directory, String className, String[] args) {
try {
File classLoaderDirectory = new File(directory);
URL url = classLoaderDirectory.toURL();
URL[] urls = new URL[] { url };
ClassLoader loader = new URLClassLoader(urls);
Class clazz = loader.loadClass(className);
Method mainMethod = clazz.getMethod("main", String[].class);
// mainMethod.invoke(null, new Object[] { new String[] { /* args */}
// });
mainMethod.invoke(null, new Object[] { args });
} catch (Exception e) {
e.printStackTrace();
}
}
================================分隔线================================
JDK6.0中可以使用下面的方法:
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 thejavac
command.
package
org.kodejava.example.tools;
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/kodejava/example/tools/Hello.java"
);
System.out.println(
"Compile result code = "
+ result);
}
}