Skip to content
This repository has been archived by the owner on Feb 16, 2022. It is now read-only.

Commit

Permalink
Added class finder using package name.
Browse files Browse the repository at this point in the history
  • Loading branch information
StaticDefaultTester2 committed Nov 7, 2019
1 parent eb8927b commit bf974da
Showing 1 changed file with 49 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package com.realtimetech.reflection.classfile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;

public class ClassFinder {
private static void recursiveSearch(File directory, String packageName, List<Class<?>> resultClasses) throws ClassNotFoundException {
if (directory.exists()) {
File[] files = directory.listFiles();
for (File file : files) {
if (file.isDirectory()) {
recursiveSearch(file, packageName + "." + file.getName(), resultClasses);
} else if (file.getName().endsWith(".class")) {
resultClasses.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
}
}
}
}

public static Class<?>[] getClassInPackages(Class<?> packageInClass) throws IOException {
return getClassInPackages(packageInClass.getPackageName());
}

public static Class<?>[] getClassInPackages(String packageName) throws IOException {
String path = packageName.replace('.', '/');
Enumeration<URL> resources = ClassFinder.class.getClassLoader().getResources(path);
List<File> directories = new LinkedList<File>();

while (resources.hasMoreElements()) {
URL resource = resources.nextElement();
directories.add(new File(resource.getFile()));
}

LinkedList<Class<?>> resultClasses = new LinkedList<Class<?>>();

for (File directory : directories) {
try {
recursiveSearch(directory, packageName, resultClasses);
} catch (ClassNotFoundException e) {
}
}

return resultClasses.toArray(new Class<?>[resultClasses.size()]);
}
}

0 comments on commit bf974da

Please sign in to comment.