动态编译
下面的demo就涵盖了动态编译和运行类的过程
package 动态编译;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
public class Demo {
public static void main(String[] args) throws Exception {
JavaCompiler compiler=ToolProvider.getSystemJavaCompiler();
int result=( compiler.run(null,null, null,"G:/test.java"));
System.out.println(result==0?"编译成功":"编译失败");
// //1:通过runtime.getRuntime运行启动好的进程运行
// Runtime run=Runtime.getRuntime();
// Process process =run.exec("java -cp c:/myjava HelloWorld");
// InputStream io=process.getInputStream();
// BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(io));
// String info="";
// while((info= bufferedReader.readLine())!=null) {
// System.out.println(info);
// }
//2通过反射运行编译的类‘
URL [] urls=new URL[] {new URL("file:/"+"C:/myjava/")};
URLClassLoader classLoader=new URLClassLoader(urls);
Class c=classLoader.loadClass("test");
Method c1= c.getMethod("main", String[].class);
c1.invoke(null, (Object)new String[] {"aa","bb"});
//注意要加Object,否则会理解为传入aa,bb两个参数了,而不是一个数组
}
}