Problem: I have an abstract class that external users can implement. These classes will be used in my application. However I do not know these classes beforehand. I would like to load them during runtime.
Current setup: The current setup is to add the classes in a jar file and add them to the classpath when running the program. The program then searches the class path for any class files and looks whether they are not abstract, not an interface and whether they the abstract class is assignable from that class.
- Add jar files to classpath
- Start program
- For every (class or class in jar file) in class path
- check if abstract class is assignable from class and
- class is not abstract not interface
Is there a library or easy way for doing this? I'm afraid this code might be a bit error-prone.
UPDATE: Something like this?
private static <T> Class<? extends T> loadSubclasses(Class<T> superClass)
UPDATE: I think this will do the trick
I want to find the classes in order to use them later on. I think this will do the trick (still have to test this code):
public static <T> Set<Class<? extends T>>
loadSubClasses(Class<T> superClass) {
return loadSubClasses(superClass,
ClasspathHelper.staticClassLoader());
}
public static <T> Set<Class<? extends T>> loadSubClasses(
Class<T> superClass, ClassLoader classLoader) {
Reflections reflections = new Reflections(classLoader);
return reflections.getSubTypesOf(superClass);
}