java学习笔记之动态编译

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[]{});
    }
}
发布了64 篇原创文章 · 获赞 24 · 访问量 6万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览