Java Class Find findClassesAnnotatedWith(String packageName, Class a)

Here you can find the source of findClassesAnnotatedWith(String packageName, Class a)

Description

find Classes Annotated With

License

LGPL

Declaration

public static List<Class<?>> findClassesAnnotatedWith(String packageName, Class<? extends Annotation> a)
            throws IOException, ClassNotFoundException 

Method Source Code

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

import java.io.*;
import java.lang.annotation.Annotation;

import java.net.*;

import java.util.*;

public class Main {
    public static List<Class<?>> findClassesAnnotatedWith(String packageName, Class<? extends Annotation> a)
            throws IOException, ClassNotFoundException {
        List<Class<?>> classes = new ArrayList<Class<?>>();
        recurse(classes, packageName, a);
        return classes;
    }// ww  w  .j  a  v  a2  s.c o m

    private static void recurse(List<Class<?>> classes, String packageName, Class<? extends Annotation> a)
            throws ClassNotFoundException {
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        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<?> clazz = Class.forName(name);
                        if (clazz.isAnnotationPresent(a))
                            classes.add(clazz);
                    } else if (new File(filePath, file).isDirectory()) {
                        recurse(classes, packageName + "." + file, a);
                    }
                }
            }
        }
    }
}

Related

  1. findAllClasses(String packageName)
  2. findClass(String packageName, Class[] superClass)
  3. findClassBase(Class clazz)
  4. findClasses(String directory, String packageName)
  5. findClasses(String path, String packageName)
  6. findClassesAssignableFrom(String packageName, Class assignableFrom)
  7. findClassLocation(Class context)
  8. findClassOriginFile(Class cls)
  9. getAllAssignedClass(Class cls)