/** * @param fqcn * Name of superclass/interface on which to search */ public final Vector<Class<?>> findClassesInPackage(String packageName) { synchronized (classpathLocations) { synchronized (results) { errors = new ArrayList<Throwable>(); results = new TreeMap<Class<?>, URL>(CLASS_COMPARATOR); return findSubclasses(classpathLocations, packageName); } } }
/** * Rescan the classpath, cacheing all possible file locations. */ public final void refreshLocations() { synchronized (classpathLocations) { classpathLocations = getClasspathLocations(); } }
public ClassFinder() { refreshLocations(); }
finder = new ClassFinder(); v = finder.findClassesInPackage(args[0]); errors = finder.getErrors(); } else { System.out.println("Usage: java ClassFinder <package.name>"); if (v != null && v.size() > 0) { for (Class<?> cls : v) { System.out.println(cls + " in " + ((finder != null) ? String.valueOf(finder.getLocationOf(cls)) : "?"));
private final void include(String name, File file, Map<URL, String> map) { if (!file.exists()) return; if (!file.isDirectory()) { // could be a JAR file includeJar(file, map); return; } if (name == null) { name = ""; } else { name += "."; } // add subpackages File[] dirs = file.listFiles(DIRECTORIES_ONLY); for (int i = 0; i < dirs.length; i++) { try { // add the present package map.put(new URL("file://" + dirs[i].getCanonicalPath()), name + dirs[i].getName()); } catch (IOException ioe) { return; } include(name + dirs[i].getName(), dirs[i], map); } }
/** * Determine every URL location defined by the current classpath, and it's associated package name. */ public final Map<URL, String> getClasspathLocations() { Map<URL, String> map = new TreeMap<URL, String>(URL_COMPARATOR); File file = null; String pathSep = System.getProperty("path.separator"); String classpath = System.getProperty("java.class.path"); StringTokenizer st = new StringTokenizer(classpath, pathSep); while (st.hasMoreTokens()) { String path = st.nextToken(); file = new File(path); include(null, file, map); } return map; }
map.put(new URL(jarURL.toExternalForm() + entry.getName()), packageNameFor(entry)); } catch (MalformedURLException murl) {
private final Vector<Class<?>> findSubclasses(Map<URL, String> locations, String searchingPackageName) { Vector<Class<?>> v = new Vector<Class<?>>(); Vector<Class<?>> w = null; Iterator<URL> it = locations.keySet().iterator(); while (it.hasNext()) { URL url = it.next(); //search just required packages String packageName = locations.get(url); if (packageName.startsWith(searchingPackageName)) { w = findSubclasses(url, packageName, searchingPackageName); if (w != null && (w.size() > 0)) { v.addAll(w); } } } return v; }