kc2001
kc2001

Reputation: 5247

What is an efficient way of finding the classes in a project using Eclipse's JDT?

Eclipse's SearchEngine class has many methods for searching, including various flavors of search, searchAllTypeNames, etc. searchAllTypeNames seems to be oriented around finding the classes in a package. What is a good strategy for finding the user-defined classes in a project? (By user-defined classes, I mean classes for which the user has written source code which resides in that project, as opposed to classes which are imported from other projects, external jars, system libraries, etc.)

  1. Use search with a custom IJavaSearchResultCollector.
  2. Obtain all of the packages in the project (using search?), then iterate through the packages, collecting the classes using searchAllTypeNames.
  3. Traverse the AST manually.
  4. Something else.

Note, I don't really need the "most efficient" way of collecting classes. I prefer something that is easy-to-code and reasonably efficient to something that requires large amounts of code to be more efficient.

I welcome any related, general guidance on using the SearchEngine methods. I find the many options baffling.

Upvotes: 0

Views: 134

Answers (1)

Andrew Eisenberg
Andrew Eisenberg

Reputation: 28757

Since your search criteria are fairly specific, your best bet is to traverse the Java model to find your types.

Here is a little loop that you can use:

    IJavaProject proj = getJavaProject();
    for (IPackageFragmentRoot root : prog.getAllPackageFragmentRoots()) {
        if (!root.isReadOnly()) {
            for (IJavaElement child : root.getChildren()) {
                if (child.getElementType() == IJavaElement.PACKAGE_FRAGMENT) {
                    IPackageFragment frag = (IPackageFragment) child;
                    for (ICompilationUnit u : frag.getCompilationUnits()) {
                        for (IType type : u.getAllTypes()) {
                            if (type.isClass() || type.isEnum()) {
                                // do something
                            }
                        }
                    }
                }
            }
        }
    }

I recommend a loop like this rather than using the search engine since there is no easy way that I know of to use the search engine to only find source types.

Upvotes: 1

Related Questions