0
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.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578

1 Answers1

0

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.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578