如何获取java编译器?
获取java编译器可以动态编译java文件,获取方式有以下几种。
一,使用Runtime
Runtime.getRuntime().exec(“javac c://test.java”);执行cmd命令进行编译.java文件,详情请见:
https://blog.csdn.net/rico_zhou/article/details/79873344
二,通过系统方法getSystemJavaCompiler方法获取
注意,查看源码是可以发现此方法获取的还是tools.jar,但是此文件在java/jdk/lib下,需要将其复制到jdk/jre/lib下,不然返回的是null。
// 第一种,使用系统方法获取 public static JavaCompiler getJavaCompiler1() { //需要把jdk/lib下的tools.jar复制到jdk/jre/lib下 JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); return compiler; }
三,从安装的jdk中获取
主要是找到tools.jar文件,读取环境变量,拼接路径,然后从中获取编译器。
// 第二种,使用环境变量从jdk中读取 public static JavaCompiler getJavaCompiler2() throws Exception { String javahome = System.getenv("JAVA_HOME"); File file = new File(javahome + File.separator + "lib\\tools.jar"); if (!file.exists()) { return null; } JavaCompiler compiler = getJavaCompilerByLocation(file); return compiler; } // 获取编译器 public static JavaCompiler getJavaCompilerByLocation(File f1) throws Exception { String p = f1.getAbsolutePath(); URL[] urls = new URL[] { new URL("file:/" + p) }; URLClassLoader myClassLoader1 = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader()); Class<?> myClass1 = myClassLoader1.loadClass("com.sun.tools.javac.api.JavacTool"); JavaCompiler compiler = myClass1.asSubclass(JavaCompiler.class).asSubclass(JavaCompiler.class).newInstance(); return compiler; }
四,从指定的tools.jar获取
需要jar包tools.jar,传入路径参数,代码如下
// 第三种,任意目录下tools.jar读取 public static JavaCompiler getJavaCompiler3(String filePath) throws Exception { File file = new File(filePath); if (!file.exists()) { return null; } JavaCompiler compiler = getJavaCompilerByLocation(file); return compiler; } // 获取编译器 public static JavaCompiler getJavaCompilerByLocation(File f1) throws Exception { String p = f1.getAbsolutePath(); URL[] urls = new URL[] { new URL("file:/" + p) }; URLClassLoader myClassLoader1 = new URLClassLoader(urls, Thread.currentThread().getContextClassLoader()); Class<?> myClass1 = myClassLoader1.loadClass("com.sun.tools.javac.api.JavacTool"); JavaCompiler compiler = myClass1.asSubclass(JavaCompiler.class).asSubclass(JavaCompiler.class).newInstance(); return compiler; }
归根结底,最主要的还是tools.jar文件,demo源码GitHub:https://github.com/ricozhou/getjavacompiler