One option is using java.lang.reflect.Method
, as explained in Bozho's answers. It's very flexible, but the main drawbacks are that you lose all type safety - there is no check that you are calling the method with the right parameters (and expect the right return type).
So if you later change the method, and forget to change all callers, you'll only find out at runtime (through a ClassCastException
). Even the method name is only checked at runtime (because you fetch it by name.
An alternative is to use callbacks via interfaces. A method that wants to accept another method as a parameter just expects an instance of a certain interface. The interface only has one method, doStuff
. Then you can create instances that implement the interface, and pass those to the methods. That's a bit more verbose (because you need the interface), but typesafe and thus easier to refactor.
That is more or less the command pattern, BTW.