2011-05-21 43 views
2

創建方法:與我剛剛發現這個方法函數參數

new Thread(
      new Runnable() { 
       public void run() { 
        try { 
         // MY CODE 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } 
       } 
      }).start(); 

我不知道如果我可以創建一個參數的方法是,我會投入到//我的代碼的功能。我可以這樣做嗎?和如何:)

回答

4

Java不支持(它可以作爲參數被傳遞或從方法返回即函數)第一類函數。

但是你可以使用策略模式的某種變體來代替:創建一些接口Executable與方法execute,並通過它的匿名實現作爲參數:

interface Executable { 

    void execute(); 
} 

... 
void someMethod(final Executable ex) { 
//here's your code 
     new Thread(
      new Runnable() { 
       public void run() { 
        try { 
         ex.execute(); // <----here we use passed 'function' 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } 
       } 
     }).start(); 
} 

... 

//here we call it: 

someMethod(new Executable() { 
    public void execute() { 
     System.out.println("hello"); // MY CODE section goes here 
    } 
}); 
+0

C#支持嗎?對不起,但我想知道它:) – nXqd 2011-05-21 07:00:18

+1

@nXqd:比Java更大的程度。 C#有委託人,這是一類公民。你最好單獨提問,熟悉C#的人會給你一個很好的答案。 – Roman 2011-05-21 07:04:03

2

這實際上是創建一個匿名類對象(實現Runnable接口)。所以你只傳遞類對象。這只是一種速記符號。

這對於您不打算重用/引用您的調用代碼內再次創建該對象的情況下特別有用。

現在對於你的問題 - 你可以創造出期望的對象的功能,如上文所述,同時呼籲你可以傳遞所需的對象/匿名類對象。

1

更高層次的語言,如Common Lisp的和Python有first-class functions,這是你在找什麼。 Java沒有這個功能。相反,你必須使用接口。 C和C++允許將函數指針作爲參數傳遞。 C++也有function objects

相關問題