Tuesday, 10 September 2013

How to call a method by name (String) in Java?

How to call a method by name (String) in Java?

Every instance of class A has an instance of class B. A should call
different methods in B depending on its member variable method_num. This
is an implementation that does what I want:
public class A {
private B myB = new B();
public int method_num = 1;
public callBMethod() {
if ( method_num == 1 )
myB.method1();
else
myB.method2();
}
}
public class B {
public method1() { }
public method2() { }
}
But instead of doing myA.method_num = 1, I want to be able to somehow pass
B's method1 or method2 directly. How can I do that?

No comments:

Post a Comment