javaCompiler简析

Posted shaomys

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javaCompiler简析相关的知识,希望对你有一定的参考价值。

  javaCompiler简单来说就是一个用来调用java语言编译器的接口,我们使用它可以实现对其他路径下或者远程代码的编译。

显然我们可以实现这样一种操作,将一串符合java语法的字符串写入一个java文件中。然后利用javaCompiler编译此文件。最后通过

反射的方法实现对此文件的运行(online judge)。

  

public static void main(String[] args) throws Exception {
        /**
         * 将 string 写入Hello.java中
         * 通过文件输出流
         */
        String string = "public class Hello { public static void main(String []args){System.out.println("Hello");}}";
        File file = new File("C:\Users\Administrator\Desktop\temp\Hello.java");
        if (!file.exists()) {
            file.createNewFile();
        }
        byte[] bytes = string.getBytes();
        FileOutputStream stream = new FileOutputStream(file);
        stream.write(bytes, 0, bytes.length);
        stream.close();
        /**
         * 编译Hello.java
         * 通过反射调用main函数实现函数的运行
         */
        JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
        int result = javaCompiler.run(null, null, null, "C:\Users\Administrator\Desktop\temp\Hello.java");
        System.out.println(result == 0 ? "success" : "failure");
        URL[] urls = new URL[]{new URL("file:/" + "C:/Users/Administrator/Desktop/temp/")};
        URLClassLoader classLoader = new URLClassLoader(urls);
        Class c = classLoader.loadClass("Hello");
        System.out.println(c.getName());
        Method method = c.getDeclaredMethod("main", String[].class);
        method.invoke(null,  (Object) new String[]{"aa","bb"});
    }

  

 

以上是关于javaCompiler简析的主要内容,如果未能解决你的问题,请参考以下文章

Android WebView远程代码执行漏洞简析

javajavac 相关API JavaCompiler StandardJavaFileManager AbstractProcessor

智能机器人编程游戏robocode的运行代码简析

简析静态xml布局如何通过动态代码实现

功能强大的图片截取修剪神器:Android SimpleCropView及其实例代码重用简析(转)

简析Jenkins的SVN插件未更新到最新代码