利用JavaCompiler对文件进行动态编译,JDK1.6新增特性
package com.xiva.test;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.ToolProvider;
import com.xiva.domain.JavaStringObject;
public class IvDynamicClass
{
public static JavaFileObject getFileObject()
{
JavaFileObject fileObj = new JavaStringObject(null, null);
return fileObj;
}
@SuppressWarnings("unchecked")
public static void testFileDynamicCompile() throws Exception
{
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int result = compiler.run(null, null, null, "E:\\data\\com\\xiva\\test\\ConsoleDemo.java");
System.out.println(result);
URL[] urls = new URL[]{new URL("file:E:/data/")};
URLClassLoader loader = new URLClassLoader(urls);
Class clazz = loader.loadClass("com.xiva.test.ConsoleDemo");
Method method = clazz.getMethod("main", String[].class);
Object [] argsMain = {null};
method.invoke(clazz.newInstance(), argsMain);
}
public static void main(String[] args) throws Exception
{
testFileDynamicCompile();
}
}