最近花時間解決了一些以前積攢的,未曾深入研究的問題。其中一個就是eclipse maven 關聯jar包源代碼出現亂碼的問題。問題的解決方案不算太麻煩,但是追本溯源確是件很有意思的事情(一直追蹤到eclipse的源代碼,探查到一些開源項目,如:伊利諾斯大學的開源項目CodingSpectator)。當然了,RCP開發本身就挺吸引我的,後面有機會,會和大家分享更多的心得。好了,廢話不說,既然知道了存在亂碼問題,那麼我們想想,eclipse maven插件是怎麼綁定源代碼的(恩,底層肯定調用了JDT API,是 吧)?面向對象一個很重要的特性就是繼承,而約定大於配置的法則則充分將這一特性發揮到了極致(繼承式資源lookup模式),只不過這個默認契約對於開發人員來講是黑盒的(Toolkit,文檔,源碼都是很好的查看工具)。經過一陣子定位跟蹤,我發現了代碼源頭(https://github.com/eclipse/eclipse.jdt.core/blob/master/org.eclipse.jdt.core/model/org/eclipse/jdt/internal/core/SourceMapper.java),關鍵代碼如下:
/**
* Creates a <code>SourceMapper</code> that locates source in the zip file
* at the given location in the specified package fragment root.
*/
public SourceMapper(IPath sourcePath, String rootPath, Map options, String encoding) {
this.areRootPathsComputed = false;
this.options = options;
this.encoding = encoding;
try {
this.defaultEncoding = ResourcesPlugin.getWorkspace().getRoot().getDefaultCharset();
} catch (CoreException e) {
// use no encoding
}
if (rootPath != null) {
this.rootPaths = new ArrayList();
this.rootPaths.add(rootPath);
}
this.sourcePath = sourcePath;
this.sourceRanges = new HashMap();
this.parametersRanges = new HashMap();
this.parameterNames = new HashMap();
this.importsTable = new HashMap();
this.importsCounterTable = new HashMap();
}
通過這裏的分析,我們可以很清晰的看到,只要修改Eclipse的window -> Preferences -> General -> Workspace->Text file encoding,而不用修改project的默認編碼就能非常完美的解決問題,不是嗎!?
好了,今天就到這裏吧。後面還會陸續推出一些源碼賞析的文章,希望感興趣的同學能繼續關注,多多交流~
參考資料:
2. http://wiki.eclipse.org/CVS_Howto
3. http://www.vogella.com/articles/EclipseCodeAccess/article.html