2

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);
}
Ash Bel
  • 83
  • 5
  • what do you mean by "loading" classes? generics as you suggested will definitely not do anything like this during runtime at least, it is for ensuring compile time safety. depending on what you actually want to do, reflection might be the solution. – Vegard Jun 01 '13 at 06:08
  • Your question might be already answered [here](http://stackoverflow.com/questions/492184/how-do-you-find-all-subclasses-of-a-given-class-in-java) – Arend Jun 01 '13 at 07:11
  • 1. [Get a list of resources from classpath directory](http://stackoverflow.com/questions/3923129/get-a-list-of-resources-from-classpath-directory), 2. Check the class: `AbstractPlugin.class.isAssignableFrom(clazz)`, `Modifier.isInterface(clazz.getModifiers())`, `Modifier.isAbstract(clazz.getModifiers())` 3. You should use a special plug-in directory and check it for any changes or you have to keep a list of all previous scanned jars in your classpath and check it to improve the startup time. – Jarandinor Jun 01 '13 at 07:28
  • Solved. See UPDATE section. Thx for your attention. – Ash Bel Jun 01 '13 at 08:31

0 Answers0