追本溯源 - Eclipse源码窥探
最近花时间解决了一些以前积攒的,未曾深入研究的问题。其中一个就是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. https://wiki.eclipse.org/CVS_Howto
3. https://www.vogella.com/articles/EclipseCodeAccess/article.html
最后更新:2017-04-02 16:47:44