Skip to content

Instantly share code, notes, and snippets.

@doojinkang
Created April 25, 2021 14:43
Show Gist options
  • Save doojinkang/a38fdd6a1f70d1e537a9b6202627dff5 to your computer and use it in GitHub Desktop.
Save doojinkang/a38fdd6a1f70d1e537a9b6202627dff5 to your computer and use it in GitHub Desktop.
Get Classes from package name
public static Class[] getClasses(String packageName)
throws ClassNotFoundException, IOException {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
assert classLoader != null;
String path = packageName.replace('.', '/');
Enumeration resources = classLoader.getResources(path);
List<File> dirs = new ArrayList<File>();
while (resources.hasMoreElements()) {
URL resource = (URL) resources.nextElement();
dirs.add(new File(resource.getFile()));
}
List<Class> classes = new ArrayList<Class>();
for (File directory : dirs) {
classes.addAll(findClasses(directory, packageName));
}
return classes.toArray(new Class[classes.size()]);
}
private static List findClasses(File directory, String packageName) throws ClassNotFoundException {
List 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, packageName + "." + file.getName()));
} else if (file.getName().endsWith(".class")) {
classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
}
}
return classes;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment