SearchPackageClassUtil { @NotNull public static String[] searchPackageClass(@NotNull String packageName) { String packageDirName = packageName.replace('.', '/'); Enumeration<URL> resources = null; try { resources = Thread.currentThread().getContextClassLoader().getResources(packageDirName); } catch (IOException e) { e.printStackTrace(); } if (!resources.hasMoreElements()) { throw new IllegalArgumentException("找不到此包"); } Set<String> classNames = new HashSet<>(); do { URL url = resources.nextElement(); String protocol = url.getProtocol(); if ("file".equals(protocol)) { String filePath = null; try { filePath = URLDecoder.decode(url.getFile(), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } File file = new File(filePath); searchByClass0(file, packageName, classNames); } else if ("jar".equals(protocol)) { try { JarFile jarFile = ((JarURLConnection) url.openConnection()).getJarFile(); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { JarEntry jarEntry = entries.nextElement(); if (jarEntry.getName().startsWith(packageDirName)) { if (jarEntry.getName().endsWith(".class")) { classNames.add(jarEntry.getName().replace('/', '.')); } } } } catch (IOException e) { e.printStackTrace(); } } } while (resources.hasMoreElements()); String[] names = classNames.toArray(new String[0]); for (int i = 0; i < names.length; i++) { names[i] = names[i].substring(0, names[i].length() - 6); } return names; }  @NotNull static String[] searchPackageClass(@NotNull String packageName);  }
@Test @DisplayName("不存在的包的处理") void searchPackageClassNotExits() { assertThrows(IllegalArgumentException.class, () -> { String[] nothings = SearchPackageClassUtil.searchPackageClass("nothing"); for (String core : nothings) { System.out.println(core); } }); }
@Test @DisplayName("包名输错") void searchPackageClassWrongType() { assertThrows(IllegalArgumentException.class, () -> { String[] nothings = SearchPackageClassUtil.searchPackageClass("SearchPackageClassUtilTest.class"); for (String core : nothings) { System.out.println(core); } }); }