import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import com.sun.tools.javac.Main;
class ExecJava {
public static void runJava(String code) {
File file;
Main javac = new Main();
String classname = "";
String filename = "";
String path = System.getProperty("user.dir")+"\\work";
try {
// 在当前目录下产生一个临时JAVA文件
file = new File(path+"\\TTTTT.java");
file.createNewFile();
// 当程序离开时删除这个临时文件
filename = file.getName();
classname = getClassName(filename);
// 写临时文件
PrintWriter out = new PrintWriter(new FileOutputStream(file));
out.print("package com.work;\r\n");
out.print("public class " + classname + "{\r\n");
out.print("\tpublic static void main(String[] test) {\r\n");
out.print("\t\t");
out.println(code);
out.println("test();");
out.println("\t}");
out.print("\tpublic static void test() {\r\n");
out.print("\t\t");
out.println(code);
out.println("\t}");
out.println("\r\n}");
out.flush();
out.close();
// 编译执行临时文件
String[] args = new String[] { "-d",path, path+"\\"+ filename };
int status = javac.compile(args);
new File(file.getParent(), classname + ".class");
// System.out.println(classname);
System.setProperty("java.class.path", path);
Class clss = Class.forName("com.work.TTTTT");
System.out.println(clss.getPackage());
Method m = clss.getMethod("test", null);
m.invoke(clss,null);
} catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
/** 根据一个java源文件名获得类名 */
private static String getClassName(String filename) {
return filename.substring(0, filename.length() - 5);
}
public static void main(String args[]) {
runJava("System.out.println(\"test\");");
}
}
</script>