Guava: Get All Classes by a Package Name

Created on 23 Aug 2017  路  7Comments  路  Source: google/guava

I needed a way to get all classes that starts with a certain package name, followed by a ".".
The only way to do that is by getting all the classes (ClassPath.getAllClasses()) and filtering the result by yourself. There's no reason that we could only get the top classes by a certin package name, and not all.
I'm asking for a simple change, to add the following 2 methodes:

  /** Returns all classes whose package name is {@code packageName}. */
  public ImmutableSet<ClassInfo> getAllClasses(String packageName) {
    checkNotNull(packageName);
    ImmutableSet.Builder<ClassInfo> builder = ImmutableSet.builder();
    for (ClassInfo classInfo : getAllClasses()) {
      if (classInfo.getPackageName().equals(packageName)) {
        builder.add(classInfo);
      }
    }
    return builder.build();
  }

  /**
   * Returns all classes whose package name is {@code packageName} or starts with
   * {@code packageName} followed by a '.'.
   */
  public ImmutableSet<ClassInfo> getAllClassesRecursive(String packageName) {
    checkNotNull(packageName);
    String packagePrefix = packageName + '.';
    ImmutableSet.Builder<ClassInfo> builder = ImmutableSet.builder();
    for (ClassInfo classInfo : getAllClasses()) {
      if (classInfo.getName().startsWith(packagePrefix)) {
        builder.add(classInfo);
      }
    }
    return builder.build();
  }
package=reflect type=enhancement

All 7 comments

I need all the classes, that's including inner classes, not just top level classes.

Oh, I was misled by code (getTopLevelClasses() instead of getAllClasses() in for loops). It makes sense now.

You are correct, my bad. Edited.

One more catch: in getAllClassesRecursive(String packageName), similar to ClassPath.html#line.151, you should check that classInfo.getName().startsWith(packagePrefix) instead of classInfo.getPackageName().startsWith(packagePrefix), otherwise you exclude base package (packageName doesn't start with packageName + ".").

Thanks again man! Fixed

I don't think the code that this saves is common enough/complicated enough to warrant a method in Guava. It's also much simpler with Streams.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Hanmac picture Hanmac  路  3Comments

gissuebot picture gissuebot  路  5Comments

cpovirk picture cpovirk  路  5Comments

epkugelmass picture epkugelmass  路  4Comments

terence1984 picture terence1984  路  3Comments