Java Class Find getAllClasses(String packageName)

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

Description

get All Classes

License

Apache License

Declaration

@SuppressWarnings("rawtypes")
    public static List<Class> getAllClasses(String packageName) throws ClassNotFoundException 

Method Source Code


//package com.java2s;
//License from project: Apache License 

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

public class Main {
    @SuppressWarnings("rawtypes")
    public static List<Class> getAllClasses(String packageName) throws ClassNotFoundException {
        ArrayList<Class> classes = new ArrayList<Class>();
        File directory = null;//from  w  ww  .  ja  va 2 s .c  o  m
        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            if (classLoader == null)
                throw new ClassNotFoundException("Can't get class loader.");
            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 a");
        }
        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 b");
        }
        return classes;
    }
}

Related

  1. findClassesAssignableFrom(String packageName, Class assignableFrom)
  2. findClassLocation(Class context)
  3. findClassOriginFile(Class cls)
  4. getAllAssignedClass(Class cls)
  5. getAllClasses(ClassLoader cl, String packageName)
  6. getAllClassesFromPackage(final String packageName)
  7. getAllClassesIn(String... packageNames)
  8. getAllClassesInPackage(String packageName)
  9. getClasses(Class clazz)