2011-09-18 64 views
1

我在嘗試創建一個函數調用列表。我希望能夠通過簡單地從數組中選擇方法來調用特定的方法。如何在Java中動態創建方法調用

因此,例如,如果我想調用drawCircle(),並且該方法在第一個索引中比我可以說runMethod [0]。

這是我到目前爲止。我做了一個接口有兩個輸入:

public interface Instruction { 
    void instr(int a, int b); 
} 

在我的其他類我有一個方法列表(或他們應該是實現教學班?)。我想能夠從列表中調用任何這些方法,如下所示:

instList[0].mov(1, 3); 
instList[2].add(4, 5); 

等等。希望已經夠清楚了。提前致謝。

+1

你可能想看看使用[Command Design Pattern](http://en.wikipedia.org/wiki/Command_pattern)。對此,你已經在使用接口了。 :) –

+4

不應該是'instList [0] .instr(1,3);'? – svick

回答

1

如果「動態調用方法調用」是指對接口進行方法調用,並讓Java選擇執行哪個代碼:這只是通過動態調度的多態性,因此提供了不同的實現:

class Mov implements Instruction { 
    void instr(int a, int b) { 
     // code for moving here 
    } 
} 

class Add implements Instruction { 
    void instr(int a, int b) { 
     // code for adding here 
    } 
} 

然後,您可以使用這些實現的實例,例如,在一個數組中。當致電instr時,動態調度將爲每個實例選擇正確的代碼。但我想知道這樣一個通用接口和一系列實現實例是否是一個好設計。如果可以的話,我會使用更具體的接口並將實例保存在單獨的變量中。你的做法有一定道理,如果你想實現Command模式,即您

  • 有不同的客戶,應該能夠處理的命令組不同,或
  • 要排隊或記錄或撤銷/重做所有命令。

如果「做出方法動態調用」你的意思是duck typing,這只是一個可能艱難的方式,請參閱this conference paper on the International Conference on Software Engineering 2011

5

除非我誤解你想達到什麼目的,這樣做的普通的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 
    } 
} 

現在:

Instruction[] instructions = new Instruction[5]; 
instructions[0] = new MoveInstruction(); 
instructions[2] = new AddInstruction(); 

... 

instructions[0].instr(1, 3); 
instructions[2].instr(4, 5); 

如果你只使用MoveInstruction/AddInstruction類是在設置陣列時,anonymous classes是使其更快一點的好方法。

1

看起來你正在試圖做的是使用函數指針,這在Java中不存在,儘管它看起來並不像你在這種情況下肯定需要使用它們。你可以做的是使用像這樣的常規switch語句。

public static void runMethod(int whichone) 
{ 
    switch(whichone) 
    { 
     case 0: drawCircle(); break; 
     case 1: etc... break; 
    } 

} 

然後你可以用適當的參數調用runMethod。

public static void main(Strign[] args) 
{ 
    runMethod(0); 
    runMethod(3); 
    etc... 
} 
1

再次,命令模式,你可以用地圖實現...

import java.util.HashMap; 
import java.util.Map; 

public class CommandEg { 
    private static Map<String, Instruction> instructionMap = new HashMap<String, Instruction>(); 

    public static void main(String[] args) { 
     instructionMap.put("mov", new Instruction() { 
     public void instr(int a, int b) { 
      // TODO: code to do mov action 
     } 
     }); 
     instructionMap.put("add", new Instruction() { 
     public void instr(int a, int b) { 
      // TODO: code to do add action 
     } 
     }); 

     instructionMap.get("mov").instr(1, 4); 
     instructionMap.get("add").instr(4, 8); 
    } 

} 

interface Instruction { 
    void instr(int a, int b); 
} 
0

你可以使用簡單的開關情況吧....

switch(function)//function is an int value 
{ 
case 1:circle(); 
case 2:rectangle(); 
. 
. 
. 
}