在基于JDT做插件开发时,经常会碰到希望根据类名直接得到ICompilationUnit或IJavaElement,来访问这个类的JavaModel,但发现要实现这个实在是好困难,主要是因中JDT中SearchEngine的文档或例子代码简直找不到,只能从eclipse的jdt源码中学习,总结了一些使用经验:
1.根据类名得到符合条件SearMatch
public class SearchEngineUtils {
/** *//**
*
* @param clsName
* @return
*/
public static List<SearchMatch> searchClass(final String clsName) {
final List<SearchMatch> matchs = new ArrayList<SearchMatch>();
SearchRequestor requestor = new SearchRequestor() {
@Override
public void acceptSearchMatch(SearchMatch match) throws CoreException {
if (match.getResource().getName().lastIndexOf(clsName) > -1)
matchs.add(match);
}
};
SearchPattern pattern = SearchPattern.createPattern(clsName, IJavaSearchConstants.CLASS, IJavaSearchConstants.DECLARATIONS,
SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE);
IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
try {
new SearchEngine().search(pattern, new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope, requestor, null);
} catch (Exception e) {
e.printStackTrace();
}
return matchs;
}
}
2.从SearchMatch得到ICompilationUnit或IJavaElement
使用org.eclipse.jdt.internal.corext.util.SearchUtils,虽然它是一个内部类,但好象还没找到替代它的.