package proxy;
import java.lang.reflect.Constructor;
import java.net.URL;
import java.net.URLClassLoader;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
public class MyCompiler {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
//编译java源代码
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager fileManager = compiler.getStandardFileManager(
null, null, null);
String fileName = System.getProperty("user.dir")+"/src/proxy/Hello.java";
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(fileName);
JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager,
null, null, null, compilationUnits);
Boolean success = task.call();
fileManager.close();
System.out.println("Success: " + success);
//load into memory and instance
URL[] urls = new URL[]{new URL("file:/"+ System.getProperty("user.dir")+"/src")};
System.out.println(urls[0]);
URLClassLoader ucl = new URLClassLoader(urls);
Class c = ucl.loadClass("proxy.Hello");
System.out.println(c);
Constructor constructor = c.getConstructor(null);
Hello o = (Hello)constructor.newInstance(null);
//调用具体的方法
o.test();
}
}