更新時間:2021-05-25 15:24:55 來源:動力節點 瀏覽989次
Java是一個開放的平臺,對于除發布編譯器/解釋器/基礎類庫之外,該語言的負責機構更多的是制定一系列標準,任何符合標準的廠商產品均可用于市場投放。甚至包括其編譯器及解釋器。
(比如Hibernate提供了JPA實現;Tomcat實現了Java EE服務器標準,其Servlet容器通過了Java認證;各數據庫或中間件廠商也根據JDBC接口開發驅動。說白了,Java基本就是都提供接口,然后讓廠商開發實現,因此有時候我會罵,邊罵邊編碼!)
GCC有java編譯器,可以看看。
我們主要主要介紹Eclipse自己開發和使用的針對Java的編譯器:(ecj)the Eclipse Compiler for Java。Eclipse沒有使用JDK自帶的編譯器,而是自己開發的,ecj也通過了java的驗證。
除了Eclipse之外,Tomcat也用到了Ecj,用于動態編譯jsp文件。我們安裝Tomcat后可在lib文件夾下找到ecj:
現在問題來了:怎么取得ecj源碼呢?
別急,我們從tomcat源碼中查看一下:
下面是我下載好后倒入項目文件后截圖:
這個文件報錯,不過可以把他刪除了看,我先沒有刪除,因為這個文件是ecj與ant的橋梁。從源碼可以看出這個JDTCompilerAdapter是繼承自ant的DefaultCompilerAdapter,用于ant的編譯器適配器。個人感覺ecj從代碼(技術)上并沒有耦合任何一個調用者,這里的ant也只是一個適配器,你刪除或者留著沒有任何影響。Tomcat里也沒有使用ant。
我從這里主要是想看看高層怎么調用ecj來編譯代碼,我們看看關鍵代碼:
private static String compilerClass = "org.eclipse.jdt.internal.compiler.batch.Main"; //$NON-NLS-1$
/**
* Performs a compile using the JDT batch compiler
* @throws BuildException if anything wrong happen during the compilation
* @return boolean true if the compilation is ok, false otherwise
*/
public boolean execute() throws BuildException {
this.attributes.log(AntAdapterMessages.getString("ant.jdtadapter.info.usingJDTCompiler"), Project.MSG_VERBOSE); //$NON-NLS-1$
Commandline cmd = setupJavacCommand();
try {
Class c = Class.forName(compilerClass);
Constructor batchCompilerConstructor =
c.getConstructor(new Class[] {
PrintWriter.class,
PrintWriter.class,
Boolean.TYPE,
Map.class});
Object batchCompilerInstance =
batchCompilerConstructor.newInstance(new Object[] {
new PrintWriter(System.out),
new PrintWriter(System.err),
Boolean.TRUE,
this.customDefaultOptions});
Method compile =
c.getMethod("compile", new Class[] {String[].class}); //$NON-NLS-1$
Object result =
compile.invoke(batchCompilerInstance, new Object[] {
cmd.getArguments()});
final boolean resultValue = ((Boolean) result).booleanValue();
if (!resultValue && this.logFileName != null) {
this.attributes.log(AntAdapterMessages.getString("ant.jdtadapter.error.compilationFailed", this.logFileName)); //$NON-NLS-1$
}
return resultValue;
} catch (ClassNotFoundException cnfe) {
throw new BuildException(AntAdapterMessages.getString("ant.jdtadapter.error.cannotFindJDTCompiler")); //$NON-NLS-1$
} catch (Exception ex) {
throw new BuildException(ex);
}
}
我把代碼換了下行,大家看13和26行,可以看出這里使用了
org.eclipse.jdt.internal.compiler.batch.Main#compile(String[])方法來進行編譯,我們可以稍微看看:
從源碼上來看1664是配置,1684可能是編譯,不過我們先不細看。
我們再看看Tomcat怎么使用ecj的,我們查看org.apache.jasper.compiler.JDTCompiler源碼(我貼出了源碼,不過有點長):
從427可以知道,Tomcat使用了org.eclipse.jdt.internal.compiler.Compiler#compile(ICompilationUnit[])
當然,在這之前使用了很多代碼來進行配置。
以上就是動力節點小編介紹的"Java編譯器eclipse的主要分析",希望對大家有幫助,如有疑問,請在線咨詢,有專業老師隨時為您服務。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習