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();
}
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.