Created
August 5, 2011 20:45
-
-
Save JimmyFrix/1128480 to your computer and use it in GitHub Desktop.
A utility class for loading and listing classes from a package.
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
package org.odysseus.util; | |
import java.io.File; | |
import java.util.ArrayList; | |
import java.util.List; | |
/** | |
* A utility class for classes. | |
* | |
* @author Jimmy Frix | |
*/ | |
public class ClassUtils { | |
/** | |
* Finds all of the classes from a specified package, loads them, and adds them to a list to | |
* return. | |
* | |
* @param packageName | |
* The package to list the classes from. | |
* @return The list of classes from the package. | |
* @throws ClassNotFoundException | |
*/ | |
public static List<Class<?>> listClassesFromPackage(String packageName) | |
throws ClassNotFoundException { | |
List<Class<?>> list = new ArrayList<>(); | |
File file = new File("./bin/" + packageName.replace('.', '/') + "/"); | |
if (file.exists() && file.isDirectory()) { | |
for (File f : file.listFiles()) { | |
if (f.getName().endsWith(".class")) { | |
list.add(Class.forName(packageName + "." | |
+ f.getName().substring(0, f.getName().length() - 6))); | |
} | |
} | |
} | |
return list; | |
} | |
/** | |
* Loads all classes for a specified package. | |
* | |
* @param packageName | |
* The package to loads the classes from. | |
* @throws ClassNotFoundException | |
*/ | |
public static void loadClassesFromPackage(String packageName) throws ClassNotFoundException { | |
File file = new File("./bin/" + packageName.replace('.', '/') + "/"); | |
if (file.exists() && file.isDirectory()) { | |
for (File f : file.listFiles()) { | |
if (f.getName().endsWith(".class")) { | |
Class.forName(packageName + "." | |
+ f.getName().substring(0, f.getName().length() - 6)); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment