Reputation: 25
I want to call a method by using a string. I get that this is possible; from what I understand reflection is the way to go. However, I'm having a hard time getting it to work and this is what I want.
For instance:
String method ="punch";
int punch(){
return 1;
}
I want to call the method by the string name. Can someone show me an example?
public class foo {
String method ="punch";
int punch() {
return 1;
}
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Class<?> myClass = Class.forName("foo");
Method myMethod = myClass.getMethod("punch");
Object retObject = myMethod.invoke(null);
}
}
What do I need to do so that I can get the number 1?
Upvotes: 0
Views: 98
Reputation: 262474
Object retObject = myMethod.invoke(null);
That would only work for a static method.
For an instance method, you need to pass in the instance that you want to invoke the method on.
Object retObject = myMethod.invoke(instanceOfFoo);
Also, the method may need to be public
(or be made accessible separately).
Upvotes: 5