Well, you can achieve this using reflection.
public void bMethod(String name) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { A.class.getMethod(name).invoke(null); }
Where name is the name of your method (be it aMethod1 or aMethod2 ).
However, this is not a real OOP method, and you should use a different approach. For example, define an interface named Behavior
interface Behavior { void run(); }
Then you create two different implementations of this interface.
class BehaviorA implements Behavior { @Override public void run() {
Now your bMethod signature inside your class B might look like this:
void bMethod(Behavior b);
And voila! You can pass two different behaviors to your method now, without using ugly reflection-based hacks.
source share