class A {
method x() {
}
method y() {
}
}
class B {
A a = new A();
String methodName = "x";
// I want to execute this statement **a.x();**
}
I know the method name and I want to call the method automatically.
class A {
method x() {
}
method y() {
}
}
class B {
A a = new A();
String methodName = "x";
// I want to execute this statement **a.x();**
}
I know the method name and I want to call the method automatically.
In your case just call:
a.getClass().getMethod(methodName, null).invoke(a);
Remember about thrown exceptions:
NoSuchMethodException
InvocationTargetException
IllegalAccessException
And make x
method public or just use getDeclaredMethod
instead of getMethod
.