find Class In Dir - Java Reflection

Java examples for Reflection:Class Loader

Description

find Class In Dir

Demo Code


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

import java.util.List;

public class Main {


    private static void findClassInDir(File directory, String packageName,
            List<Class<?>> classes, boolean annotated)
            throws ClassNotFoundException {
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                findClassInDir(file, packageName + "." + file.getName(),
                        classes, annotated);
            } else if (file.getName().endsWith(".class")) {
                Class<?> clazz = Class.forName(packageName
                        + '.'
                        + file.getName().substring(0,
                                file.getName().length() - 6));
                if (!annotated || clazz.getAnnotations().length > 0) {
                    classes.add(clazz);/*from w  w  w. j  a  v  a  2  s  . c  o m*/
                }
            }
        }
    }
}

Related Tutorials