I have a generic string stored in a variable String func = "validate"; and i want to call the function of that name ie, i need to call validate() function.
I mean to say i will pass the variable to some function
public void callFunc(String func){
....
}
so, the above function should call the appropriate function with function name passed as a parameter to the callfunc().
-
A common example is loading the appropriate JDBC driver with Class.forName(): xyzws.com/Javafaq/what-does-classforname-method-do/17paulsm4– paulsm42012-05-09 06:23:17 +00:00Commented May 9, 2012 at 6:23
2 Answers
You can use reflection to do this, e.g.
Method method = getClass().getMethod(func);
// TODO: Validation
method.invoke(this);
That's assuming you want to call the method on this, of course, and that it's an instance method. Look at Class.getMethod and related methods, along with Method itself, for more details. You may want getDeclaredMethod instead, and you may need to make it accessible.
I would see if you can think of a way of avoiding this if possible though - reflection tends to get messy quickly. It's worth taking a step back and considering if this is the best design. If you give us more details of the bigger picture, we may be able to suggest alternatives.
8 Comments
func(val1, val2)invoke(this, val1, val2). Read the documentation I've linked to.method.invoke(this).callFunc2() ? @JonSkeetThere is another way than using reflections. You can write a pattern matching like the following:
switch (func) {
case "validate": validate(); break;
case "apply": apply(); break;
default: break;
}
But I agree with Jon: try to avoid this. If you use pattern matching you have to apply changes twice. If you add another method for example, you need to add it to the function naming method and to the pattern matching.
2 Comments
mypage() then again i need to add mypage case in switch function.