Java Class Find findClassesAssignableFrom(String packageName, Class assignableFrom)

Here you can find the source of findClassesAssignableFrom(String packageName, Class assignableFrom)

Description

find Classes Assignable From

License

LGPL

Declaration

public static <T> Set<Class<T>> findClassesAssignableFrom(String packageName, Class<T> assignableFrom)
            throws IOException, ClassNotFoundException 

Method Source Code

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

import java.io.*;

import java.net.*;

import java.util.*;

public class Main {
    public static <T> Set<Class<T>> findClassesAssignableFrom(String packageName, Class<T> assignableFrom)
            throws IOException, ClassNotFoundException {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        Set<Class<T>> classes = new HashSet<Class<T>>();
        String path = packageName.replace('.', '/');
        URL resource = loader.getResource(path);
        if (resource != null) {
            String filePath = resource.getFile();
            if (filePath != null && new File(filePath).isDirectory()) {
                for (String file : new File(filePath).list()) {
                    if (file.endsWith(".class")) {
                        String name = packageName + '.' + file.substring(0, file.indexOf(".class"));
                        Class<T> clazz = (Class<T>) Class.forName(name);
                        if (assignableFrom.isAssignableFrom(clazz))
                            classes.add(clazz);
                    }/*from   w  w w.  j  ava  2 s.  c  o  m*/
                }
            }
        }
        return classes;
    }
}

Related

  1. findClass(String packageName, Class[] superClass)
  2. findClassBase(Class clazz)
  3. findClasses(String directory, String packageName)
  4. findClasses(String path, String packageName)
  5. findClassesAnnotatedWith(String packageName, Class a)
  6. findClassLocation(Class context)
  7. findClassOriginFile(Class cls)
  8. getAllAssignedClass(Class cls)
  9. getAllClasses(ClassLoader cl, String packageName)