Java Class from Package getClasses(String packageName)

Here you can find the source of getClasses(String packageName)

Description

Returns all classes from specified package.

License

Open Source License

Parameter

Parameter Description

Return

array of classes.

Declaration

public static Class[] getClasses(String packageName) throws ClassNotFoundException 

Method Source Code


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

import java.io.File;
import java.net.URL;
import java.util.ArrayList;

public class Main {
    /**//from   w  ww  . j a  v a2  s .  c  o m
     * Returns all classes from specified package.
     * @param pckgname, full name of package.
     * @return array of classes.
     */
    public static Class[] getClasses(String packageName) throws ClassNotFoundException {
        ArrayList<Class> classes = new ArrayList<Class>();
        // Get a File object for the package
        File directory = null;
        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            if (classLoader == null) {
                throw new ClassNotFoundException("Can't get class loader.");
            }
            //String path = '/' + pckgname.replace('.', '/');
            String path = packageName.replace('.', '/');
            URL resource = classLoader.getResource(path);
            if (resource == null) {
                throw new ClassNotFoundException("No resource for " + path);
            }
            directory = new File(resource.getFile());
        } catch (NullPointerException x) {
            throw new ClassNotFoundException(
                    packageName + " (" + directory + ") does not appear to be a valid package");
        }
        if (directory.exists()) {
            // Get the list of the files contained in the package
            String[] files = directory.list();
            for (int i = 0; i < files.length; i++) {
                // we are only interested in .class files
                if (files[i].endsWith(".class")) {
                    // removes the .class extension
                    classes.add(Class.forName(packageName + '.' + files[i].substring(0, files[i].length() - 6)));
                }
            }
        } else {
            throw new ClassNotFoundException(packageName + " does not appear to be a valid package");
        }
        Class[] classesA = new Class[classes.size()];
        classes.toArray(classesA);
        return classesA;
    }
}

Related

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