Skip to content

Instantly share code, notes, and snippets.

@khotyn
Created December 27, 2011 11:32
Show Gist options
  • Save khotyn/1523363 to your computer and use it in GitHub Desktop.
Save khotyn/1523363 to your computer and use it in GitHub Desktop.
Read all the classes in the class path.
package com.khotyn.test;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* A utility that can read all the classes in the class path.
*
* @author khotyn 2011-11-29 上午9:34:25
*/
public class ClassUtil {
/**
* Get all the classes that defined under the class path.
*
* @return
* @throws IOException
*/
public static List<String> getClassesFromClassPath() throws IOException {
String[] classPathes = System.getProperty("java.class.path").split(":");
List<String> result = new ArrayList<String>();
for (String classPath : classPathes) {
File classPathFile = new File(classPath);
if (classPathFile.isDirectory()) {
List<String> children = getSubFiles(classPathFile);
for (String child : children) {
String pathRelativeToClassPath = child.substring(classPathFile.getAbsolutePath().length() + 1);
if (pathRelativeToClassPath.endsWith(".class")) {
result.add(pathRelativeToClassPath.replace('/', '.').replace(".class", ""));
}
}
} else if (classPath.endsWith("jar")) {
JarFile classJar = new JarFile(classPathFile);
Enumeration<JarEntry> classEntries = classJar.entries();
while (classEntries.hasMoreElements()) {
JarEntry classEntry = classEntries.nextElement();
if (classEntry.getName().endsWith(".class")) {
result.add(classEntry.getName().replace("/", ".").replace(".class", ""));
}
}
}
}
return result;
}
private static List<String> getSubFiles(File orgFile) {
List<String> subFiles = new ArrayList<String>();
if (orgFile.isDirectory()) {
File[] files = orgFile.listFiles();
for (File subFile : files) {
if (subFile.isDirectory()) {
subFiles.addAll(getSubFiles(subFile));
} else {
subFiles.add(subFile.getAbsolutePath());
}
}
}
return subFiles;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment