import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
/**
* 动态编译Java代码
*/
public class DynamicCompileTest {
public static void main(String[] args) {
File file = null;
String classname = null;
try {
String classDir = System.getProperty("user.dir");
file = File.createTempFile("RunTime", ".java", new File(classDir));
String filename = file.getName();
classname = filename.substring(0, filename.lastIndexOf('.'));
PrintWriter out = new PrintWriter(new FileOutputStream(file));
// 代码
String code = "public class " + classname + " {"
+ "public void run() {"
+ "System.out.println(\"DynamicCompile Success.\");" + "}}";
out.println(code);
out.flush();
out.close();
// 编译
String[] arg = new String[] { "-d", classDir, filename };
com.sun.tools.javac.Main.compile(arg);// JAVA_HOME/jdk/lib/tools.jar
URL url = new URL("file:/" + classDir + File.separator);
// 动态加载/执行
URLClassLoader loader = new URLClassLoader(new URL[] { url });
Class<?> clazz = loader.loadClass(classname);
Object obj = clazz.newInstance();
Method method = clazz.getMethod("run");
method.invoke(obj);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (file != null) {
file.delete();
file = new File(classname + ".class");
if (file != null)
file.delete();
}
}
}
}
代码参考了其它网站。