java获取包下所有java类

java获取包下所有java类

简单加载包下的类,注意简单编写非递归查找,自行实现递归查找即可

import java.io.File;
import java.net.URL;
import java.util.Enumeration;

/**
 * @author lingkang
 * @date 2021/12/3
 */
public class ClassUtils {
	// getClassName("top.lingkang.demohibernate.entity")
    public static Class[] getClassByPackage(String packageName) {
        try {
            Enumeration<URL> resources = ClassUtils.class.getClassLoader().getResources(packageName.replaceAll("\\.", "/"));
            while (resources.hasMoreElements()) {
                URL url = resources.nextElement();
                String[] file = new File(url.getFile()).list();
                Class[] classList = new Class[file.length];
                for (int i = 0; i < file.length; i++) {
                    classList[i] = Class.forName(packageName + "." + file[i].replaceAll("\\.class", ""));
                }
                return classList;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
posted @ 2022-09-16 00:08  凌康  阅读(233)  评论(0编辑  收藏  举报