private static void addLocalClass(List<String> classList, String packageName, String path) { try { File file = new File(path); if (file.isDirectory()) { String[] paths = file.list(); for (int i = 0; i < paths.length; i++) { if (path.endsWith("/")) { addLocalClass(classList, packageName + "." + paths[i], path + paths[i]); } else { addLocalClass(classList, packageName + "." + paths[i], path + "/" + paths[i]); } } } else { if (file.getName().endsWith(".class")) { if (file.getName().indexOf("$") == -1) { if (packageName.endsWith(".class")) { packageName = packageName.replaceFirst("." + file.getName(), ""); } classList.add( packageName + "." + file.getName().substring(0, file.getName().length() - 6)); } } } } catch (Exception e) { logger.error(e.getMessage(), e); } }
public static List<String> getClassListInPackage(String packageName) { String packagePath = packageName.replace('.', '/') + "/"; List<String> reClassList = new ArrayList<String>(); Set<String> pathSet = new HashSet<>(); URL resource = LocalResourcesUtil.class.getClassLoader().getResource(packagePath); if (resource != null) { String filePath = resource.getPath(); if (filePath.indexOf("jar!") > -1) { filePath = filePath.replaceFirst("!/" + packagePath, ""); pathSet.add(filePath); } else { addLocalClass(reClassList, packageName, filePath); if (reClassList.size() > 0) { return reClassList; } } } else { pathSet = getClassOrJarPaths(); } Iterator<String> paths = pathSet.iterator(); while (paths.hasNext()) { String path = paths.next(); try { File classPath; if (path.startsWith("file:")) { classPath = new File(new URI(path)); } else { classPath = new File(path); } if (!classPath.exists()) { continue; } if (classPath.isDirectory()) { File dir = new File(classPath, packagePath); if (!dir.exists()) { continue; } File[] files = dir.listFiles(); for (int f = 0; f < files.length; f++) { if (files[f].isFile()) { String clsName = files[f].getName(); clsName = packageName + "." + clsName.substring(0, clsName.length() - 6); reClassList.add(clsName); } } } else { FileInputStream fis = new FileInputStream(classPath); JarInputStream jis = new JarInputStream(fis, false); JarEntry entry = null; while ((entry = jis.getNextJarEntry()) != null) { String eName = entry.getName(); if (eName.startsWith(packagePath) && !eName.endsWith("/")) { reClassList.add(eName.replace('/', '.').substring(0, eName.length() - 6)); } jis.closeEntry(); } jis.close(); } } catch (IOException e) { logger.error(e.getMessage(), e); } catch (URISyntaxException e) { logger.error(e.getMessage(), e); } } return reClassList; }