java动态编译源代码并调用其中的方法

 

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();
	}

}
 

 

你可能感兴趣的:(java,源代码,动态,编译,调用内部方法)