Here you can find the source of getClassesInDirectory(File directory, String packageName, ClassLoader classLoader)
private static List<Class<?>> getClassesInDirectory(File directory, String packageName, ClassLoader classLoader) throws UnsupportedEncodingException
//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); } }