private static List<Class<?>> getClassesInDirectory( File directory, String packageName, ClassLoader classLoader) throws UnsupportedEncodingException { List<Class<?>> classes = new ArrayList<Class<?>>(); // Capture all the .class files in this directory // Get the list of the files contained in the package String[] files = directory.list(); for (String currentFile : files) { // we are only interested in .class files if (currentFile.endsWith(".class")) { // removes the .class extension // CHECKSTYLE:OFF try { classes.add( Class.forName( packageName + '.' + currentFile.substring(0, currentFile.length() - 6))); } catch (Throwable e) { // do nothing. this class hasn't been found by the loader, and we don't care. } // CHECKSTYLE:ON } else { // It's another package String subPackageName = packageName + '.' + currentFile; // Ask for all resources for the path URL resource = classLoader.getResource(subPackageName.replace('.', '/')); File subDirectory = new File(URLDecoder.decode(resource.getPath(), "UTF-8")); List<Class<?>> classesForSubPackage = getClassesInDirectory(subDirectory, subPackageName, classLoader); classes.addAll(classesForSubPackage); } } return classes; }
/** * Retrieves recursively all the classes belonging to a package. * * @param packageName * @param classLoader the class loader used to load the class in the given package * @return the list of Class found * @throws ClassNotFoundException if any error occurs */ public static List<Class<?>> getClassesInPackage(String packageName, ClassLoader classLoader) throws ClassNotFoundException { try { if (classLoader == null) { throw new ClassNotFoundException("Can't get class loader."); } String path = packageName.replace('.', '/'); // Ask for all resources for the path Enumeration<URL> resources = classLoader.getResources(path); List<Class<?>> classes = new ArrayList<Class<?>>(); while (resources.hasMoreElements()) { URL resource = resources.nextElement(); File directory = new File(URLDecoder.decode(resource.getPath(), "UTF-8")); if (directory.canRead()) { classes.addAll(getClassesInDirectory(directory, packageName, classLoader)); } else { // it's a jar file classes.addAll( getClassesInJarFile( directory.getPath().substring(5, directory.getPath().indexOf(".jar") + 4), packageName)); } } return classes; } catch (NullPointerException x) { throw new ClassNotFoundException( packageName + " does not appear to be a valid package (Null pointer exception)", x); } catch (UnsupportedEncodingException encex) { throw new ClassNotFoundException( packageName + " does not appear to be a valid package (Unsupported encoding)", encex); } catch (IOException ioex) { throw new ClassNotFoundException( "IOException was thrown when trying to get all resources for " + packageName, ioex); } }