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

Commit

Permalink
Merge pull request #3 from StaticDefault/master
Browse files Browse the repository at this point in the history
Added class finder using package name.
  • Loading branch information
StaticDefaultTester2 authored Nov 7, 2019
2 parents c064caa + bf974da commit a6debb4
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 a6debb4

Please sign in to comment.