I’m trying to make a list of function calls. I want to be able to call a specific method by simply choosing the method from an array.
So for example if I want to call, drawCircle() and that method is in the first index than I could say runMethod[0].
Here’s what I have so far. I’ve made an interface with two inputs:
public interface Instruction {
void instr( int a, int b );
}
In my other class I have a list of methods (or should they be classes that implement Instruction?). I want to be able to call any of these methods from a list, like so:
instList[0].mov( 1, 3 );
instList[2].add( 4, 5 );
and so on. Hope that was clear enough. Thanks in advance.
If by “make method calls dynamically” you mean making method calls against an interface and let Java choose which code is executed: This is simply polymorphism via dynamic dispatch, so provide different implementations:
You can then use instances of these implementations, e.g. in an array. Dynamic dispatch will choose the right code for each instance when calling
instr. But I wonder if such a general interface and an array of implementing instances is a good design. If I could, I’d use more specific interfaces and hold instances in separate variables. Your approach does make sense if you want to implement the Command pattern, i.e. youIf by “make method calls dynamically” you mean duck typing, this is only in a difficult way possible, see this conference paper on the International Conference on Software Engineering 2011.