0

I'm trying to load & create all classes that implements specific

interface in java using reflection?

Say i have :

package Test;

interface foo {}
class one implements foo {
}
class two implements foo {
}

how it can be done?

can u assist?

user10776203
  • 181
  • 3
  • 9
  • 1
    Take a look at this answer: https://stackoverflow.com/a/9240969/5759072 – Matthew May 30 '19 at 11:32
  • Look for the ServiceLoader mechanism. There is a decent explanation of it in the above mentioned answer (#2), but one can find better explanations – benji2505 May 30 '19 at 12:55

1 Answers1

0

You can look in a specific package and iterate in all classes (I just copy and past the code, follow the link). Then, you test if it uses a specific interface.

public static void main(String[] args) throws Exception{
   List<Class> classes = getClasses(ClassWithMain.class.getClassLoader(), "fr/jamailun/test");
   for(Class c : classes){
      for(Class i : c.getInterfaces()) {
         if(i.isAssignableFrom(FooInterface.class)) {
            System.out.println("The class " + c + "implements interface "+FooInterface);
            //your code then
         }
      }
   }
}

public static List<Class> getClasses(ClassLoader cl, String pack) throws Exception {
   String dottedPackage = pack.replaceAll("[/]", ".");
   List<Class> classes = new ArrayList<>();
   URL uPackage = cl.getResource(pack);
   DataInputStream dis = new DataInputStream((InputStream) uPackage.getContent());
   String line;
   while ((line = dis.readLine()) != null) {
      if(line.endsWith(".class")) {
          classes.add(Class.forName(dottedPackage+"."+line.substring(0,line.lastIndexOf('.'))));
      }
   }
   return classes;
}

Notice that "ClassWithMain" is here the class that contains this main method : could be anywhere just change the name.

Jamailun
  • 48
  • 7