通過一個介面查詢實現該介面的所有的實現類【工具包ClassUtils】
阿新 • • 發佈:2020-12-16
通過一個介面查詢實現該介面的所有的實現類【工具包ClassUtils】
public class ClassUtils { // 給一個介面,返回所有介面的實現類 public static List<Class> getAllClassByInterface(Class c) throws Exception { List<Class> resultClassList = new ArrayList<>(); // 返回結果 if (c.isInterface()) { // 判斷是否為介面 String name = c.getPackage().getName(); // 獲取當前包名 List<Class> allClass =getClass(name); for (int i = 0; i < allClass.size(); i++) { if (c.isAssignableFrom(allClass.get(i))) { if (!c.equals(allClass.get(i))) { resultClassList.add(allClass.get(i)); } } } } else { System.out.println("該Class不是一個介面"); } return resultClassList; } private static List<Class> getClass(String name) throws Exception { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); String path = name.replace(".", "/"); Enumeration<URL> resources = classLoader.getResources(path); List<File> fileList = new ArrayList<>(); while (resources.hasMoreElements()) { URL url = resources.nextElement(); fileList.add(new File(url.getFile())); } List<Class> classes = new ArrayList<>(); for (File directory : fileList) { classes.addAll(findClasses(directory, name)); } return classes; } private static List<Class> findClasses(File directory, String name) throws Exception { List<Class> classes = new ArrayList<>(); if (!directory.exists()) { return classes; } File[] files = directory.listFiles(); for (File file : files) { if (file.isDirectory()) { assert !file.getName().contains("."); classes.addAll(findClasses(file, name + "." + file.getName())); } else if (file.getName().endsWith(".class")) { classes.add(Class.forName(name + '.' + file.getName().substring(0, file.getName().length() - 6))); } } return classes; } }