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[]{});
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值