獲取Java編譯器

如何獲取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

發佈了56 篇原創文章 · 獲贊 42 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章