1

What is the best way to call a base function on all the implementations of an interface with reflection and fewer lines possible?

public interface BaseClass { public void doSomething();}

public class A implements BaseClass { 
     @Override
     public void doSomething () {
         System.out.println("doing Something in A"); 
     }
}

public class B implements BaseClass { 
     @Override
     public void doSomething () {
         System.out.println("doing Something in B"); 
     }
}

public class anotherClass {
    public static void main(final String[] args) {
       // get all the implementations of BaseClass;
       // for each implementation call doSomething();
    }
}
GhostCat
  • 137,827
  • 25
  • 176
  • 248
Vivek Kumar
  • 419
  • 4
  • 12

1 Answers1

1

Complicated:

  • scan the complete classpath for all classes
  • for each class (besides the ones coming with the JVM): check if the class extends your base class
    • if so - see if you can instantiate an object of that class to call that function on

And then realize that this does not make sense in the real world and decide to solve the underlying problem in a different way.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Would it make sense if I will write a method which will return array of objects (of implementations of interface)? But in that case, every time a new implementation is added, this method would require a change. – Vivek Kumar Jul 17 '17 at 04:07
  • Such a method makes the complicated scan part go away. But yes, you have to remember to update that method constantly. Beyond that: what is the purpose of this exercise? As said - I am wondering about the real practical need for such a solution. – GhostCat Jul 17 '17 at 04:19
  • Lets assume that the baseClass is upload interface and implementations can be 1) UploadToS3 2) UploadToRemoteHost 3)UploadToABackupServer. For some reason I want to upload my file to all the servers and in future if a new implementation is added i will need the file to be uploaded there also. Is there any other way I can achieve this? – Vivek Kumar Jul 17 '17 at 04:26
  • Use something like https://docs.oracle.com/javase/7/docs/api/java/util/ServiceLoader.html, or dependency injection. – Louis Wasserman Jul 17 '17 at 04:33