Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Get all classes within a package

The code below gets all classes within a given package. Notice that it should only work for classes found locally, getting really ALL classes is impossible.

   1  
   2      /**
   3       * Scans all classes accessible from the context class loader which belong to the given package and subpackages.
   4       *
   5       * @param packageName The base package
   6       * @return The classes
   7       * @throws ClassNotFoundException
   8       * @throws IOException
   9       */
  10      private static Class[] getClasses(String packageName)
  11              throws ClassNotFoundException, IOException {
  12          ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
  13          assert classLoader != null;
  14          String path = packageName.replace('.', '/');
  15          Enumeration<URL> resources = classLoader.getResources(path);
  16          List<File> dirs = new ArrayList<File>();
  17          while (resources.hasMoreElements()) {
  18              URL resource = resources.nextElement();
  19              dirs.add(new File(resource.getFile()));
  20          }
  21          ArrayList<Class> classes = new ArrayList<Class>();
  22          for (File directory : dirs) {
  23              classes.addAll(findClasses(directory, packageName));
  24          }
  25          return classes.toArray(new Class[classes.size()]);
  26      }
  27  
  28      /**
  29       * Recursive method used to find all classes in a given directory and subdirs.
  30       *
  31       * @param directory   The base directory
  32       * @param packageName The package name for classes found inside the base directory
  33       * @return The classes
  34       * @throws ClassNotFoundException
  35       */
  36      private static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException {
  37          List<Class> classes = new ArrayList<Class>();
  38          if (!directory.exists()) {
  39              return classes;
  40          }
  41          File[] files = directory.listFiles();
  42          for (File file : files) {
  43              if (file.isDirectory()) {
  44                  assert !file.getName().contains(".");
  45                  classes.addAll(findClasses(file, packageName + "." + file.getName()));
  46              } else if (file.getName().endsWith(".class")) {
  47                  classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
  48              }
  49          }
  50          return classes;
  51      }
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS