This repository has been archived by the owner on Feb 16, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #3 from StaticDefault/master
Added class finder using package name.
- Loading branch information
Showing
1 changed file
with
49 additions
and
0 deletions.
There are no files selected for viewing
49 changes: 49 additions & 0 deletions
49
src/main/java/com/realtimetech/reflection/classfile/ClassFinder.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()]); | ||
} | ||
} |