Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call a java method using a variable name?

Say I have Method1(void), Method2(void)...

Is there a way i can chose one of those with a variable?

 String MyVar=2;
 MethodMyVar();
like image 866
Adam Outler Avatar asked Nov 09 '10 20:11

Adam Outler


People also ask

How can we use variable as a method name in Java?

String MyVar=2; MethodMyVar(); java.

How do you call a method using variables?

To call a method in Java from another class is very simple. We can call a method from another class by just creating an object of that class inside another class. After creating an object, call methods using the object reference variable.

How do you call a method name in Java?

To call a method in Java, simply write the method's name followed by two parentheses () and a semicolon(;). If the method has parameters in the declaration, those parameters are passed within the parentheses () but this time without their datatypes specified.


2 Answers

Use reflection:

Method method = WhateverYourClassIs.class.getDeclaredMethod("Method" + MyVar); method.invoke(); 
like image 131
Nathan Hughes Avatar answered Sep 24 '22 21:09

Nathan Hughes


Only through reflection. See the java.lang.reflect package.

You could try something like:

Method m = obj.getClass().getMethod("methodName" + MyVar);
m.invoke(obj);

Your code may be different if the method has parameters and there's all sorts of exception handling missing.

But ask your self if this is really necessary? Can something be changed about your design to avoid this. Reflection code is difficult to understand and is slower than just calling obj.someMethod().

Good luck. Happy Coding.

like image 44
Todd Avatar answered Sep 23 '22 21:09

Todd