Java Class from Package getClassesForPackage(final String packageName)

Here you can find the source of getClassesForPackage(final String packageName)

Description

Attempts to list all the classes in the specified package as determined by the context class loader.

License

Open Source License

Parameter

Parameter Description
packageName The package name to search

Exception

Parameter Description
ClassNotFoundException If something went wrong

Return

List of classes that exist within that package

Declaration

public static List<Class<?>> getClassesForPackage(final String packageName) throws ClassNotFoundException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.File;

import java.io.IOException;

import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;

import java.util.ArrayList;

import java.util.Enumeration;
import java.util.List;

public class Main {
    /**//  ww  w  .j  a  va 2 s. c o m
      * Attempts to list all the classes in the specified package as determined
      * by the context class loader.
      * 
      * @param packageName The package name to search
      * @return List of classes that exist within that package
      * @throws ClassNotFoundException If something went wrong
      */
    public static List<Class<?>> getClassesForPackage(final String packageName) throws ClassNotFoundException {
        // This will hold a list of directories matching the packageName. There may be more than one if a package is split over multiple jars/paths
        ArrayList<File> directories = new ArrayList<File>();

        try {
            ClassLoader cld = Thread.currentThread().getContextClassLoader();

            if (cld == null) {
                throw new ClassNotFoundException("Can't get class loader.");
            }

            String path = packageName.replace('.', '/');

            // Ask for all resources for the path
            Enumeration<URL> resources = cld.getResources(path);
            while (resources.hasMoreElements()) {
                directories.add(new File(URLDecoder.decode(resources.nextElement().getPath(), "UTF-8")));
            }
        } 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);
        }

        ArrayList<Class<?>> classes = new ArrayList<Class<?>>();

        // For every directory identified capture all the .class files
        for (File directory : directories) {
            if (directory.exists()) {
                // Get the list of the files contained in the package
                String[] files = directory.list();

                for (String file : files) {
                    // we are only interested in .class files
                    if (file.endsWith(".class")) {
                        // removes the .class extension
                        try {
                            classes.add(Class.forName(packageName + '.' + file.substring(0, file.length() - 6)));
                        } catch (NoClassDefFoundError e) {
                            // do nothing. this class hasn't been found by the loader, and we don't care.
                        }
                    } else {
                        if (!file.contains(".")) {
                            for (Class<?> subPackageClass : getClassesForPackage(packageName + "." + file)) {
                                classes.add(subPackageClass);
                            }
                        }
                    }
                }
            } else {
                throw new ClassNotFoundException(
                        packageName + " (" + directory.getPath() + ") does not appear to be a valid package");
            }
        }

        return classes;
    }
}

Related

  1. getClasses(String packageName, Class inheritedType)
  2. getClasses(String pckgname)
  3. getClasses(String pckgname)
  4. getClasses(String pkg)
  5. getClasses(String pkg)
  6. getClassesForPackage(Package pkg)
  7. getClassesForPackage(String packageName)
  8. getClassesForPackage(String packageName)
  9. getClassesForPackage(String pckgname)