Skip to content

Instantly share code, notes, and snippets.

@adamtowerz
Created November 8, 2013 08:22
Show Gist options
  • Save adamtowerz/7367929 to your computer and use it in GitHub Desktop.
Save adamtowerz/7367929 to your computer and use it in GitHub Desktop.
A java method used to locate and return all classes in a folder that extend a certain class (input), it takes a package string as input also (e.g. "example.example2"
package me.project.fileSearch;
import java.io.File;
import java.io.FilenameFilter;
import java.net.URL;
import java.util.List;
public class ClassFinder{
public static <R extends T, T> List<T> search(String packageName, List<T> list, Class<T> type) throws ClassNotFoundException, InstantiationException, IllegalAccessException{
URL root = Thread.currentThread().getContextClassLoader().getResource(packageName.replace(".", "/"));
// Filter .class files.
File[] files = new File(root.getFile()).listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".class");
}
});
// Find classes implementing Class<T> type.
for (File file : files) {
String className = file.getName().replaceAll(".class$", "");
Class<R> cls = (Class<R>) Class.forName(packageName + "." + className);
if(cls != null && cls.getSuperclass() == type){
T elem = cls.newInstance();
list.add(elem);
}
}
return list;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment