Java Class Loader loadClassesImplementsTheInterface(String packageName, Class interfaceClazz)

Here you can find the source of loadClassesImplementsTheInterface(String packageName, Class interfaceClazz)

Description

load Classes Implements The Interface

License

Apache License

Declaration

public static Set<Class<?>> loadClassesImplementsTheInterface(String packageName, Class<?> interfaceClazz)
            throws IOException, ClassNotFoundException 

Method Source Code


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

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;

public class Main {
    public static Set<Class<?>> loadClassesImplementsTheInterface(String packageName, Class<?> interfaceClazz)
            throws IOException, ClassNotFoundException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        assert classLoader != null;
        String path = packageName.replace(".", "/");
        Enumeration<URL> resources = classLoader.getResources(path);
        List<File> dirs = new ArrayList<>();
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            dirs.add(new File(resource.getFile()));
        }//from ww w.j av  a 2 s .  c om
        Set<Class<?>> classes = new HashSet<>();
        for (File directory : dirs) {
            classes.addAll(loadClasses(directory, packageName, interfaceClazz));
        }
        return classes;
    }

    private static List<Class<?>> loadClasses(File directory, String packageName, Class<?> interfaceClazz)
            throws ClassNotFoundException {
        List<Class<?>> classes = new ArrayList<Class<?>>();
        if (!directory.exists()) {
            return classes;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(loadClasses(file, packageName + "." + file.getName(), interfaceClazz));
            } else if (file.getName().endsWith(".class")) {
                String className = file.getName().substring(0, file.getName().length() - ".class".length());
                className = packageName + "." + className;
                Class<?> clazz = Class.forName(className);
                if (interfaceClazz != clazz && interfaceClazz.isAssignableFrom(clazz)) {
                    classes.add(clazz);
                }
            }
        }
        return classes;
    }
}

Related

  1. loadClass(String className)
  2. loadClass(String dir, String classname)
  3. loadClass(String name)
  4. loadClass(String name, Object fallbackClass)
  5. loadClasses(Collection filenames, String packageName, File outputDir)
  6. loadClassifiers(String dataDirectoryName)
  7. loadConfig(String path, ClassLoader classLoader)
  8. loadForClass(final Class clazz, final String filename)
  9. loadManifest(Class manifestFileClass)