gaijinco said:
Is there a way in Java to call a method by having its name on a
string?
something as:
void foo(){}
void bar(){}
void callFunction(String s)
{
// Call function s
}
void otherFunction()
{
callFunction("foo");
}
You can use reflection.
See example below.
Arne
============================================
import java.lang.reflect.*;
public class Refl2 {
public void m1(String a, String b) {
System.out.println("m1: " + a + " " + b);
}
public void m2(String a, String b) {
System.out.println("m2: " + a + " " + b);
}
public static void c(Object o, String methodName, String a, String b) {
try {
Class declarg[] = new Class[2];
declarg[0] = String.class;
declarg[1] = String.class;
Method m = o.getClass().getMethod(methodName, declarg);
Object callarg[] = new Object[2];
callarg[0] = a;
callarg[1] = b;
m.invoke(o, callarg);
} catch (Exception e) {
}
}
public static void main(String[] args) {
Refl2 r = new Refl2();
r.m1("a", "b");
r.m2("a", "b");
c(r, "m1","a", "b");
c(r, "m2","a", "b");
}
}