码迷,mamicode.com
首页 > 编程语言 > 详细

java 动态编译

时间:2018-03-02 20:57:47      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:ack   exception   lan   []   ace   eth   动态   system   tostring   

1.第一种方式:JavaCompiler+Runntime


public static void run() {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        int res = compiler.run(null,null,null,"G:/github/src/com/reflect/Abc.java");
        System.err.println(res == 0?"成功":"失败");
        Runtime runtime = Runtime.getRuntime();
        try {
            Process process = runtime.exec("java -cp G:/github/src/com/reflect/");
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String temp;
            while ((temp = reader.readLine())!= null){
                System.err.println(temp);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

2.第二种方式:URLClassLoader+反射


public static void run2()  throws Exception {
        URL[] urls = new URL[]{new URL("file:/"+"G:/github/src/com/reflect/"),new URL("file:/"+"G:/github/src/com/net/v1/")};
        System.err.println(Arrays.toString(urls));
        URLClassLoader loader = new URLClassLoader(urls);
        Class<?> abc = loader.loadClass("com.reflect.Abc");
        Method main = abc.getMethod("main", String[].class);
        main.invoke(null,(Object) new String[]{});
    }

java 动态编译

标签:ack   exception   lan   []   ace   eth   动态   system   tostring   

原文地址:https://www.cnblogs.com/mf001/p/8494601.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!