动态编译java程序实例

import java.io.*;
import java.lang.reflect.Method;
import com.sun.tools.javac.*;

public class RuntimeCode {

    private static Main javac = new Main();
/**等待用戶輸入JavaCode,然後編譯、執行*/
    public static void main(String[] args) throws Exception {
        String code = "";
        DataInputStream bd = new DataInputStream(System.in);
        byte[] brray= new byte[200];
        int i = bd.read(brray);
        code = new String(brray,0,i);
        run(compile(code));
        System.out.print(code);

    }
 /**編譯JavaCode,返回暫存檔案物件*/
    private synchronized static File compile(String code) throws Exception {
        File file;
        //在用戶當前文件目錄創建一個臨時代碼文件
        file = File.createTempFile("JavaRuntime", ".java", new File(System.getProperty("user.dir")));
        System.out.println(System.getProperty("user.dir"));
        //當虛擬機退出時,刪除此臨時java原始檔案
        //file.deleteOnExit();
        //獲得檔案名和類名字
        String filename = file.getName();
        String classname = getClassName(filename);
        //將代碼輸出到文件
        PrintWriter out = new PrintWriter(new FileOutputStream(file));
        //        out.println("/**");
        out.write("class "+classname+"{"+"public static void main(String[] args)"+"{");
        out.write(code);
        out.write("}}");
        //關閉文件流
        out.flush();
        out.close();
        String[] args = new String[] { "-d", System.getProperty("user.dir"),filename };
        //返回編譯的狀態代碼
        int status = javac.compile(args);
        System.out.println(status);
        return file;
    }
 //運行程序
    private static synchronized void run(File file) throws Exception {
        String filename = file.getName();
        String classname = getClassName(filename);
        //當虛擬機退出時,刪除此臨時編譯的類文件
        new File(file.getParent(),classname + ".class").deleteOnExit();
        try {
            Class cls = Class.forName(classname);
            //映射main方法
            Method main = cls.getMethod("main", new Class[] { String[].class });
            //執行main方法
            main.invoke(null, new Object[] { new String[0] });
        } catch (SecurityException se) {
        }
    }
   
    private static void debug(String msg) {
        System.err.println(msg);
    }
   
    private static String getClassName(String filename) {
        return filename.substring(0, filename.length() - 5);
    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值