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?
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?
 
    
    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.
