4

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

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

8 Comments

what if i want to pass the parameters to the function func(val1, val2)
@ShamsUdDin: Then you use invoke(this, val1, val2). Read the documentation I've linked to.
How do I invoke another method. As in something like this method.invoke(this).callFunc2() ? @JonSkeet
@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.
I know the return type at compile time
|
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.

2 Comments

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.
That is exactly what I said at the bottom.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.