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

- 9,485
- 42
- 40

- 99
- 2
- 8
-
A common example is loading the appropriate JDBC driver with Class.forName(): http://www.xyzws.com/Javafaq/what-does-classforname-method-do/17 – paulsm4 May 09 '12 at 06: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.

- 1,421,763
- 867
- 9,128
- 9,194
-
what if i want to pass the parameters to the function `func(val1, val2)` – Shams Ud Din May 09 '12 at 07:05
-
1@ShamsUdDin: Then you use `invoke(this, val1, val2)`. Read the documentation I've linked to. – Jon Skeet May 09 '12 at 07:06
-
How do I invoke another method. As in something like this `method.invoke(this).callFunc2()` ? @JonSkeet – Steve Mar 27 '18 at 14:06
-
@mypeople: You need to provide more information - e.g. whether you know the method return type at compile-time, and can just cast the result, or whether you want to invoke the *second* method with reflection too. – Jon Skeet Mar 27 '18 at 14:08
-
-
-
-
There 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.

- 3,557
- 4
- 33
- 63
-
if we use the switch function then our code will not become generic, i mean to say suppose i created a new function called `mypage()` then again i need to add mypage case in switch function. – Shams Ud Din May 09 '12 at 07:02
-