我正在尝试列出函数调用.我希望能够通过从数组中选择方法来调用特定方法.
因此,例如,如果我想调用,drawCircle()和该方法在第一个索引中,而不是我可以说runMethod [0].
这是我到目前为止所拥有的.我用两个输入创建了一个接口:
public interface Instruction {
void instr( int a, int b );
}
Run Code Online (Sandbox Code Playgroud)
在我的另一个类中,我有一个方法列表(或者它们应该是实现指令的类吗?).我希望能够从列表中调用任何这些方法,如下所示:
instList[0].mov( 1, 3 );
instList[2].add( 4, 5 );
Run Code Online (Sandbox Code Playgroud)
等等.希望足够清楚.提前致谢.
除非我误解了你想要实现的目标,否则常规的Java方法是通过实现接口:
interface Instruction {
void instr( int a, int b );
}
class MoveInstruction implements Instruction {
void instr(int a, int b) {
// do something
}
}
class AddInstruction implements Instruction {
void instr(int a, int b) {
// do something else
}
}
Run Code Online (Sandbox Code Playgroud)
现在:
Instruction[] instructions = new Instruction[5];
instructions[0] = new MoveInstruction();
instructions[2] = new AddInstruction();
...
instructions[0].instr(1, 3);
instructions[2].instr(4, 5);
Run Code Online (Sandbox Code Playgroud)
如果在设置数组时只使用MoveInstruction/ AddInstructionclasses,则匿名类是使其快一点的好方法.