动态编译

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.*;

public class Demo01 {
    public static void main(String[] args) throws IOException {
        String string="" +
                "public class Hi{" +
                "   public static void main(String[] args){ System.out.println(\"很爱很爱你\");}}";
        OutputStream os= null;
        try {
            os = new FileOutputStream(new File("D:/t/Hi.java"));
            byte[] data=string.getBytes();
            os.write(data,0,data.length);
            os.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        JavaCompiler compiler= ToolProvider.getSystemJavaCompiler();
        int result=compiler.run(null,null, null, "D:/t/Test.java","D:/t/Hi.java");
        System.out.println(result==0?"编译成功":"编译失败");
        //动态运行
        Runtime runtime=Runtime.getRuntime();
        Process process=runtime.exec("java -cp D:/t Test");
        //通过流将运行结果传过来
        InputStream is=process.getInputStream();
        BufferedReader br=new BufferedReader(new InputStreamReader(is));
        String info="";
        while (null!=(info=br.readLine())){
            System.out.println(info);
        }
        
          //通过反射动态编译

        try {
            URL[] urls=new URL[]{new URL("file:/"+"D:/t/")};
            URLClassLoader classLoader=new URLClassLoader(urls);
            Class c=classLoader.loadClass("Hi");
            Method m=c.getMethod("main",String[].class);
            m.invoke(null,(Object)new String[]{});
            //m.invoke(null,new String[]{"aa","bb"});
            //由于可变参数时JDK5.0之后才有,上面代码会编译成m.invoke(null,"aa","bb"),就发生了参数个数不匹配的问题
            //因此,必须加上(Object)转型
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();

        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值