Some solutions to finding, inspecting and examining classes are done more efficiently using a bytecode-based library than using reflection.
For instance, let's say we need to find out which classes in a series of classpaths are applications. We can do this using Brian Clapper's org.clapper.util library.
All we need to do is to install his library, currently available HERE and implement a ClassFilter interface appropriately. Basing this on the good example for ClassFinder in his Javadoc (nice to see people documenting their libraries properly), we can do the below. The source is available HERE.
import org.clapper.util.classutil.*;
import java.io.*;
import java.util.*;
public class FindApps {
public static void main(String[] args) throws Throwable {
// Arguments are a series of classpaths
ClassFinder finder = new ClassFinder();
for (String arg : args)
finder.add(new File(arg));
ClassFilter filter = new ApplicationFilter();
Collection<ClassInfo> foundClasses = new ArrayList<ClassInfo>();
finder.findClasses(foundClasses, filter);
for (ClassInfo classInfo : foundClasses)
System.out.println("Found " + classInfo.getClassName());
}
// Accept classes that have main methods
static class ApplicationFilter implements ClassFilter {
public boolean accept(ClassInfo info, ClassFinder finder) {
boolean found = false;
Iterator<MethodInfo> i = info.getMethods().iterator();
while (i.hasNext() && !found) {
found = "main".equals(i.next().getName());
}
return found;
}
}
}
import java.io.*;
import java.util.*;
public class FindApps {
public static void main(String[] args) throws Throwable {
// Arguments are a series of classpaths
ClassFinder finder = new ClassFinder();
for (String arg : args)
finder.add(new File(arg));
ClassFilter filter = new ApplicationFilter();
Collection<ClassInfo> foundClasses = new ArrayList<ClassInfo>();
finder.findClasses(foundClasses, filter);
for (ClassInfo classInfo : foundClasses)
System.out.println("Found " + classInfo.getClassName());
}
// Accept classes that have main methods
static class ApplicationFilter implements ClassFilter {
public boolean accept(ClassInfo info, ClassFinder finder) {
boolean found = false;
Iterator<MethodInfo> i = info.getMethods().iterator();
while (i.hasNext() && !found) {
found = "main".equals(i.next().getName());
}
return found;
}
}
}