Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 313
Kaleb Blue Avatar asked Jun 24 '26 01:06

Kaleb Blue


2 Answers

I suggest having a look at Class.forName ( ... ) to get the class object, Class.newInstance(); if your classes have a default constructor (or Class.getDeclaredConstructor(...) otherwise) to create a new instance and then Class.getDeclaredMethod( ... ) to find the method and invoke it.

All of this without any regard if your idea is really a good one, since I really didn't quite understand WHY you want to do what you want to do...

like image 87
Florian Schaetz Avatar answered Jun 25 '26 15:06

Florian Schaetz


interface Me {
    void runMe();
}

Then let all classes implement Me.

And have a list of Mes

List<Class<Me>> ...

Then

void test(Class<Me> cl) {
    Me me = cl.newInstance();
    me.runMe();
}
like image 26
Joop Eggen Avatar answered Jun 25 '26 16:06

Joop Eggen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!