3

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

Pau Kiat Wee
  • 9,485
  • 42
  • 40
Shams Ud Din
  • 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 Answers2

15

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
0

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.

tgr
  • 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
  • That is exactly what I said at the bottom. – tgr May 09 '12 at 07:03