通过项目下的包名获取包下的全部类

通过项目下的包名获取包下的全部类

public class GetClasses {

    public static Set<Class<?>> classes = new HashSet<>();

    public static void main(String[] args) {
        GetAllClass("com.bihang.seayatest.nio");
        System.out.println(classes.size());
    }

    public static void GetAllClass(String packageName){
        Enumeration<URL> dirs = null;
        try {
            dirs = Thread.currentThread().getContextClassLoader().getResources(packageName.replace(".","/"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (dirs.hasMoreElements()){
            //获取物理路径
            String filePath = dirs.nextElement().getFile();
            addPathToClasses(filePath,packageName,classes);
        }
    }

    public static void addPathToClasses(String classPath, String rootPackageName, Set<Class<?>> classes) {
        File file = new File(classPath);
        if (!file.exists() && !file.isDirectory())
            return;

        if (file.isDirectory()) {
            File[] list = file.listFiles();
            //如果是文件夹就需要在包名后面添加文件名
            for (File path :
                    list) {
                if (path.isDirectory())
                    addPathToClasses(path.getAbsolutePath(), rootPackageName+"."+path.getName(), classes);
                else
                    addPathToClasses(path.getAbsolutePath(), rootPackageName, classes);
            }
        } else {
            if (file.getName().endsWith(".class")){
                String className = file.getName().substring(0,
                        file.getName().length() - 6);
                try {
                    classes.add(Thread.currentThread().getContextClassLoader().loadClass(rootPackageName + '.'+ className));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

getName()方法

返回文件名称,包括后缀.

list()方法

返回文件名的数组,是String的数组。

listFiles()方法

返回文件的数组,也就是绝对路径的数组。

accept()方法

listFiles()方法会为此目录对象下的每一个文件名调用accpet()方法,来判断该文件是否包含在内,判断结果由accept()方法返回的布尔值表示。

exists()

创建之前,要通过file.exists()判断该文件或者文件夹是否已经存在,如果返回true,是不能创建的。

原文地址:https://www.cnblogs.com/bihanghang/p/10208268.html