2Sep/095
Java: Reflecting to Get All Classes in a Package
It took me a little while to figure out that Java doesn't provide a way to reflect an entire package. In other words, there is no built-in way for me to dynamically retrieve a list of all the classes in a given package in Java through reflection. So I wrote my own method to do it.
Since it took a bit of googling and effort, I thought it would be nice to share the convenience method I wrote with the world. Enjoy:
/**
* Given a package name, attempts to reflect to find all classes within the package
* on the local file system.
*
* @param packageName
* @return
*/
private static Set<Class> getClassesInPackage(String packageName) {
Set<Class> classes = new HashSet<Class>();
String packageNameSlashed = "/" + packageName.replace(".", "/")
// Get a File object for the package
URL directoryURL = Thread.currentThread().getContextClassLoader().getResource(packageNameSlashed);
if (directoryURL == null) {
LOG.warn("Could not retrieve URL resource: " + packageNameSlashed);
return classes;
}
String directoryString = directoryURL.getFile();
if (directoryString == null) {
LOG.warn("Could not find directory for URL resource: " + packageNameSlashed);
return classes;
}
File directory = new File(directoryString);
if (directory.exists()) {
// Get the list of the files contained in the package
String[] files = directory.list();
for (String fileName : files) {
// We are only interested in .class files
if (fileName.endsWith(".class")) {
// Remove the .class extension
fileName = fileName.substring(0, fileName.length() - 6);
try {
classes.add(Class.forName(packageName + "." + fileName));
} catch (ClassNotFoundException e) {
LOG.warn(packageName + "." + fileName + " does not appear to be a valid class.", e);
}
}
}
} else {
LOG.warn(packageName + " does not appear to exist as a valid package on the file system.");
}
return classes;
}
-
jpucci
-
Janice
-
Mike B.
