Java Class Find getClassesInDirectory(File directory, String packageName, ClassLoader classLoader)

Here you can find the source of getClassesInDirectory(File directory, String packageName, ClassLoader classLoader)

Description

get Classes In Directory

License

Apache License

Declaration

private static List<Class<?>> getClassesInDirectory(File directory, String packageName, ClassLoader classLoader)
            throws UnsupportedEncodingException 

Method Source Code


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

import java.io.File;

import java.io.UnsupportedEncodingException;

import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;

import java.util.List;

public class Main {
    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 {
                    String className = packageName + '.' + currentFile.substring(0, currentFile.length() - 6);
                    classes.add(loadClass(className, classLoader));
                } catch (Throwable e) {
                    // do nothing. this class hasn't been found by the loader, and we don't care.
                }// w w w . j  av  a 2  s .c o m
                // 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;
    }

    private static Class<?> loadClass(String className, ClassLoader classLoader) throws ClassNotFoundException {
        return Class.forName(className, true, classLoader);
    }
}

Related

  1. getClasses(String pack)
  2. getClasses(String pkgname, boolean flat)
  3. getClassesAsList(String pckgname, Class type)
  4. getClassesDir(Class classWithinDir)
  5. getClassesExtending(Class rootClass, String pattern)
  6. getClassesLocation(Class cls)
  7. getClassesWithInterface(String packageName, Class interfaceClazz)