Created
November 8, 2013 08:22
-
-
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"
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 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