Say I have Method1(void), Method2(void)...
Is there a way i can chose one of those with a variable?
String MyVar=2;
MethodMyVar();
String MyVar=2; MethodMyVar(); java.
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.
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.
Use reflection:
Method method = WhateverYourClassIs.class.getDeclaredMethod("Method" + MyVar); method.invoke();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With