see detail
http://stackoverflow.com/questions/520328/can-you-find-all-classes-in-a-package-using-reflection?lq=1
http://stackoverflow.com/questions/15519626/how-to-get-all-classes-names-in-a-package
with https://code.google.com/p/reflections/
Reflections reflections = new Reflections("my.project.prefix");
Set<Class<? extends SomeType>> subTypes =
reflections.getSubTypesOf(SomeType.class);
Set<Class<?>> annotated =
reflections.getTypesAnnotatedWith(SomeAnnotation.class);
native code : http://stackoverflow.com/questions/15519626/how-to-get-all-classes-names-in-a-package
public final class ClassFinder {
private final static char DOT = '.';
private final static char SLASH = '/';
private final static String CLASS_SUFFIX = ".class";
private final static String BAD_PACKAGE_ERROR =
"Unable to get resources from path '%s'. Are you sure the given '%s' package exists?";
public final static List<Class<?>> find(final String scannedPackage) {
final ClassLoader classLoader =
Thread.currentThread().getContextClassLoader();
final String scannedPath = scannedPackage.replace(DOT, SLASH);
final Enumeration<URL> resources;
try {
resources = classLoader.getResources(scannedPath);
} catch (IOException e) {
throw new IllegalArgumentException(String.format(BAD_PACKAGE_ERROR,
scannedPath,
scannedPackage),
e);
}
final List<Class<?>> classes = new LinkedList<Class<?>>();
while (resources.hasMoreElements()) {
final File file = new File(resources.nextElement().getFile());
classes.addAll(find(file, scannedPackage));
}
return classes;
}
private final static List<Class<?>> find(final File file,
final String scannedPackage) {
final List<Class<?>> classes = new LinkedList<Class<?>>();
final String resource = scannedPackage + DOT + file.getName();
if (file.isDirectory()) {
for (File nestedFile : file.listFiles()) {
classes.addAll(find(nestedFile, scannedPackage));
}
} else if (resource.endsWith(CLASS_SUFFIX)) {
final int beginIndex = 0;
final int endIndex = resource.length() - CLASS_SUFFIX.length();
final String className = resource.substring(beginIndex, endIndex);
try {
classes.add(Class.forName(className));
} catch (ClassNotFoundException ignore) {
ignore.printStackTrace();
}
}
return classes;
}
// test
public static void main(String[] args) {
List<Class<?>> classes = ClassFinder.find("***.model");
for(int i = 0; i < classes.size(); i++){
System.out.println("<class>" + classes.get(i).getName() +"</class>");
}
}
}