find Classes in directory - Java Reflection

Java examples for Reflection:Class Loader

Description

find Classes in directory

Demo Code


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

import java.util.ArrayList;

import java.util.List;

public class Main {


    @SuppressWarnings("rawtypes")
    public static List<Class> findClasses(File directory, String packageName)
            throws ClassNotFoundException {
        List<Class> classes = new ArrayList<Class>();
        if (!directory.exists()) {
            return classes;
        }/*from  w w w .  j a  va2  s . c  o  m*/
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file,
                        packageName + "." + file.getName()));
            } else if (file.getName().endsWith(".class")) {
                classes.add(Class.forName(packageName
                        + '.'
                        + file.getName().substring(0,
                                file.getName().length() - 6)));
            }
        }
        return classes;
    }
}

Related Tutorials