package com.bjsxt.test;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
public class Demon001 {
public static void main(String[] args) {
JavaCompiler compiler= ToolProvider.getSystemJavaCompiler();
int result=compiler.run(null,null,null,"D:/mycode/Welcome.java");
System.out.println(result==0?"编译成功":"编译失败");
/*
Runtime run=Runtime.getRuntime();
Process process=run.exec("java -cp D:/mycode Welcome");
InputStream is=process.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(is));
String msg="";
while((msg=reader.readLine())!=null){
System.out.println(msg);
}
*/
URL[] urls = new URL[0];
try {
urls = new URL[]{new URL("file:/"+"D:/mycode/")};
URLClassLoader loader =new URLClassLoader(urls);
Class c=loader.loadClass("Welcome");
Method m=c.getMethod("main",String[].class);
m.invoke(null,(Object)new String[]{});
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行结果:
编译成功
hi