mardi 28 juillet 2015

Design Approach and Using Reflection to run methods in Java

I have a question. I have multiple classes in a package: Let's say package is

com.myPackage.first

And this package has the following classes:

firstGood
secondGood
thirdBad
fourthGood

Each of these classes have a method with the same name but different implementation. So say each have a one particular function called:

public void runMe(){

}

For now I want to come up with a way to given a class name, it'll go inside the class and run that particular method.

So conceptually, my method will look like those:

ArrayList<Class> classList ; // where classList is a list of classes I want to run 

public void execute(){
 for(Class c : classList){
  // Go inside that class, (maybe create an intance of that class) and run     the method called run me
 }
}

or

public void execute(Class c, String methodToRun){
 for(Class c : classList){
  // Go inside that class, (maybe create an intance of that class) and    run     the method called run me
 }
}

For now. what I have been able to do is get the name of the classes I want to run the

runMe() 

method. So I have been able to come with a way to get the arraylist of classes I want to run. So what I need help with is coming up with a method such that it takes a class name and run the method I want it to. Any help is appreciated. Thanks

Aucun commentaire:

Enregistrer un commentaire