该工具类ClassUtil提供在当前类或接口遍历所有类信息、根据包名查询出所有类信息及获取指定目录&包路径下的所有类等几种方式,详情代码如下
package xwood;@b@@b@import java.io.File;@b@import java.io.IOException;@b@import java.net.URL;@b@import java.util.ArrayList;@b@import java.util.Enumeration;@b@import java.util.List;@b@ @b@public class ClassUtil {@b@ @b@ /**@b@ * 获取到当前类或接口的所有子类@b@ * @param c@b@ * @return@b@ * @throws ClassNotFoundException@b@ * @throws IOException@b@ */@b@ public static List<Class<?>> getAllClasses(Class<?> c) throws ClassNotFoundException,IOException{@b@ List<Class<?>> cls = new ArrayList<Class<?>>();@b@ String packageName = c.getPackage().getName();@b@ List<Class<?>> allClass = getClasses(packageName);@b@ for(int i = 0; i < allClass.size(); i++){@b@ if(c.isAssignableFrom(allClass.get(i))){@b@ if(!c.equals(allClass.get(i))){@b@ cls.add(allClass.get(i));@b@ }@b@ }@b@ }@b@ return cls;@b@ }@b@ @b@ /**@b@ * 根据包名查询出所有子类信息@b@ * @param packageName@b@ * @return@b@ * @throws ClassNotFoundException@b@ * @throws IOException@b@ */@b@ private static List<Class<?>> getClasses(String packageName) throws ClassNotFoundException,IOException{@b@ ClassLoader classLoader = Thread.currentThread().getContextClassLoader();@b@ String path = packageName.replace(".", "/");@b@ Enumeration<URL> resources = classLoader.getResources(path);@b@ List<File> dirs = new ArrayList<File>();@b@ while(resources.hasMoreElements()){@b@ URL resource = resources.nextElement();@b@ dirs.add(new File(resource.getFile()));@b@ }@b@ List<Class<?>> classes = new ArrayList<Class<?>>();@b@ for(File directory:dirs){@b@ classes.addAll(findClass(directory, packageName));@b@ }@b@ return classes;@b@ }@b@ @b@ /**@b@ * 获取指定目录&包路径下的所有类@b@ * @param directory 文件目录路径@b@ * @param packageName 包名路径@b@ * @return@b@ * @throws ClassNotFoundException@b@ */@b@ private static List<Class<?>> findClass(File directory, String packageName) @b@ throws ClassNotFoundException{@b@ List<Class<?>> classes = new ArrayList<Class<?>>();@b@ if(!directory.exists()){@b@ return classes;@b@ }@b@ File[] files = directory.listFiles();@b@ for(File file:files){@b@ if(file.isDirectory()){@b@ assert !file.getName().contains(".");@b@ classes.addAll(findClass(file, packageName+"."+file.getName()));@b@ }else if(file.getName().endsWith(".class")){@b@ classes.add(Class.forName(packageName+"."+file.getName().substring(0,file.getName().length()-6)));@b@ }@b@ }@b@ return classes;@b@ }@b@ @b@ public static void main(String[] args) throws Exception{@b@ //测试打印xwood包下面类@b@ List<Class<?>> _class=getClasses("xwood");@b@ for(Class cla:_class)@b@ System.out.println(cla.toString());@b@ @b@ }@b@ @b@}
测试打印xwood包下面类名称,控制台结果
class xwood.ClassUtil@b@class xwood.MethodInvoker@b@interface xwood.MyMethod@b@class xwood.Test