import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
/**
* 动态编译
*
* @author ly1
*
*/
public class DynamicCompiler {
public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
//将字符串写进文件
String str = "public class HelloWorld{public static void main(String[] args){System.out.println(\"Hello World!\");}}";
FileOutputStream fos = new FileOutputStream("src/DynamicCompiler/HelloWorld.java");
fos.write(str.getBytes());
fos.close();
//动态编译文件
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int state = compiler.run(null, null, null, "src/DynamicCompiler/HelloWorld.java");
System.out.println(state == 0 ? "编译成功" : "编译失败");
//动态运行
//第一种方式:
// Runtime run = Runtime.getRuntime();
// Process process = run.exec("java -cp src/DynamicCompiler HelloWorld");
//
// BufferedInputStream is = new BufferedInputStream(process.getInputStream());
// byte[] buffer = new byte[1024];
// int len = 0;
// while( -1 != (len = is.read(buffer))){
// System.out.println(new String(buffer,0 ,len));
// }
//
// is.close();
//第二种方式:利用反射
URL[] urls = new URL[]{new URL("file:/"+ "F:/items/eclipse items/DynamicCompiler/src/DynamicCompiler/")};
URLClassLoader loader = new URLClassLoader(urls);
Class clazz = loader.loadClass("HelloWorld");
Method method = clazz.getMethod("main", String[].class);
method.invoke(null, (Object)new String[]{});
}
}
java学习笔记之动态编译
最新推荐文章于 2021-11-03 18:05:29 发布