Java: How to call a function whose name is stored in a string variable

Shams Ud Din picture Shams Ud Din · May 9, 2012 · Viewed 7.4k times · Source

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().

Answer

Jon Skeet picture Jon Skeet · May 9, 2012

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.