Java Class Find getClassesExtending(Class rootClass, String pattern)

Here you can find the source of getClassesExtending(Class rootClass, String pattern)

Description

get Classes Extending

License

Open Source License

Declaration

public static <E> Collection<Class<? extends E>> getClassesExtending(Class<E> rootClass, String pattern)
            throws ClassNotFoundException 

Method Source Code


//package com.java2s;
import java.io.*;

import java.net.*;
import java.util.*;

public class Main {
    public static <E> Collection<Class<? extends E>> getClassesExtending(Class<E> rootClass, String pattern)
            throws ClassNotFoundException {
        ArrayList<Class<? extends E>> classes = new ArrayList<Class<? extends E>>();
        File dir = findOriginClassPath(rootClass, pattern);
        for (String filename : dir.list()) {
            if (filename.endsWith(".class")) {
                Class<?> c = Class.forName(pattern.replace('/', '.') + "." + filename.split("\\.")[0], true,
                        Thread.currentThread().getContextClassLoader());
                if (rootClass.isAssignableFrom(c) && c != rootClass) {
                    classes.add(c.asSubclass(rootClass));
                }/* w ww. jav a2 s .co  m*/
            }
        }
        return classes;
    }

    private static <E> File findOriginClassPath(Class<E> rootClass, String pattern) throws ClassNotFoundException {
        String classpathEntry = whereis(rootClass);

        File dir = new File(classpathEntry + pattern);
        System.out.println("dir = " + dir);
        if (dir.isDirectory()) {
            return dir;
        }
        throw new IllegalStateException("Could not find directory for classes");
    }

    public static String whereis(Class clazz) {
        return whereis(clazz.getName(), clazz.getClassLoader());
    }

    public static String whereis(String className, ClassLoader classloader) {
        String filename = className.replace('.', '/') + ".class";
        if (classloader == null)
            classloader = ClassLoader.getSystemClassLoader();
        URL url = classloader.getResource(filename);
        // idea from http://weblogs.java.net/blog/2007/04/25/how-convert-javaneturl-javaiofile
        File file;
        try {
            file = new File(url.toURI());
        } catch (URISyntaxException e) {
            file = new File(url.getPath());
        }

        String location = file.toString();
        location = location.substring(0, location.length() - className.length() - ".class".length());
        return location;
    }
}

Related

  1. getClasses(final String pckgname)
  2. getClasses(String pack)
  3. getClasses(String pkgname, boolean flat)
  4. getClassesAsList(String pckgname, Class type)
  5. getClassesDir(Class classWithinDir)
  6. getClassesInDirectory(File directory, String packageName, ClassLoader classLoader)
  7. getClassesLocation(Class cls)
  8. getClassesWithInterface(String packageName, Class interfaceClazz)