diff --git a/src/main/java/com/realtimetech/reflection/classfile/ClassFinder.java b/src/main/java/com/realtimetech/reflection/classfile/ClassFinder.java new file mode 100644 index 0000000..c0911ef --- /dev/null +++ b/src/main/java/com/realtimetech/reflection/classfile/ClassFinder.java @@ -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> 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 resources = ClassFinder.class.getClassLoader().getResources(path); + List directories = new LinkedList(); + + while (resources.hasMoreElements()) { + URL resource = resources.nextElement(); + directories.add(new File(resource.getFile())); + } + + LinkedList> resultClasses = new LinkedList>(); + + for (File directory : directories) { + try { + recursiveSearch(directory, packageName, resultClasses); + } catch (ClassNotFoundException e) { + } + } + + return resultClasses.toArray(new Class[resultClasses.size()]); + } +}