如何使用IJavaElement

时间:2010-01-29 05:14:08

标签: java eclipse-plugin

我正在开发一个搜索插件,我正在使用IPackageFragment来指定要在其中执行搜索的包。我无法使用IPackageFragment创建IJavaSearchScope。请通过提供适当示例的说明来帮助我。

谢谢

1 个答案:

答案 0 :(得分:2)

这个article Find unused methods中有一个很好的例子:

IPackageFragment用于获取您想要的任何Java元素(如方法)

public static List<MethodInformation>  calculate(IJavaProject project) {
  List<MethodInformation> list = new ArrayList<MethodInformation>();
  try {
    if (project.isOpen()) {
      IPackageFragment[] packages = project.getPackageFragments();
      // parse(JavaCore.create(project));
      for (IPackageFragment mypackage : packages) {
        if (mypackage.getKind() == IPackageFragmentRoot.K_SOURCE) {
          for (ICompilationUnit unit : mypackage.getCompilationUnits()) {
             IType[] types = unit.getTypes();
             for (int i = 0; i < types.length; i++) {
               IType type = types[i];
               IMethod[] methods = type.getMethods();

IJavaSearchScope是从SearchEngine创建的,并与通过IPackageFragment元素找到的元素一起使用。

    private static int  performIMethodSearch(IMethod method) throws CoreException {
      SearchPattern pattern = SearchPattern.createPattern(method, IJavaSearchConstants.REFERENCES);
      IJavaSearchScope scope = SearchEngine.createWorkspaceScope();
      MySearchRequestor requestor = new MySearchRequestor();
      SearchEngine searchEngine = new SearchEngine();
      searchEngine.search( pattern, 
                           new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, 
                           scope, requestor, null);
      return requestor.getNumberOfCalls();
    }