2012-11-06 63 views
-1

我想知道是否可以通過將函數名稱添加到參數來調用另一個函數。因此,例如,我想用4個部分製作腳本。每個部分都需要輸入(我使用掃描儀,不要問爲什麼:P是它的任務),然後需要將其傳遞給另一個腳本,例如,計算和東西。通過將其添加到參數調用另一個函數

我這個開始的:

static int intKiezer(String returnFunctie, String text) { 

    Scanner vrager = new Scanner(System.in); 
    while (true) { 

     System.out.println(text); 
     int intGekozen = vrager.nextInt(); 

     if (vrager.hasNextInt()) { 

      returnFunctie(intGekozen); 
     } 

     else { 

      vrager.next(); 
      System.out.println("Verkeerde invoer!"); 
     } 
    } 

正如你看到的,我想通過努力把它(returnFunctie(intgekozen))所獲得的價值推到另一個功能。它應該用intgekozen作爲參數調用returnFunctie。但它不起作用

我會調用這樣的函數:intKiezer(sphereCalculations, "What radius do you want to have?")。所以從輸入的答案,如果其正確的應該傳遞給另一個函數稱爲sphereCalculations

+1

你的returnFunctie(...)代碼在哪裏? – kosa

+0

原則上這可能與反思,但真正的問題是:你爲什麼想這樣做?這表明你的程序有一個奇怪的設計。 (反射只能用於特殊情況,我不想學習你的壞習慣)。 – Jesper

+0

事情是我有多個輸入,我想爲他們做一個功能。不僅僅是說明掃描儀的每種功能,例如,這對我來說似乎是最簡單的方法,因爲我只需添加文本和函數名稱 –

回答

3

這是一個想法。

定義一個接口,該接口擁有一個可以執行任何計算的方法。例如:

interface Algorithm { 
    int execute(int value); 
} 

然後定義一個或多個類來實現接口並做任何你希望他們做的計算。例如:

class MultiplyByTwo implements Algorithm { 
    public int execute(int value) { 
     return value * 2; 
    } 
} 

class AddThree implements Algorithm { 
    public int execute(int value) { 
     return value + 3; 
    } 
} 

然後,寫你的方法,使其接受一個Algorithm作爲參數。用所需的值執行算法。

static int intKiezer(Algorithm algo, String text) { 
    // ... 

    return algo.execute(intGekozen); 
} 

通過傳遞接口Algorithm的實現類的一個實例調用你的方法。

int result = intKiezer(new MultiplyByTwo(), "Some question"); 
System.out.println("Result: " + result); 
+0

好吧,我明白了:)。唯一的是我還沒有使用類。但是我試着用你告訴我的技巧編輯我的腳本。我不知道我是否正確使用它。不應該通過只加入return「returnFunctie.execute(intGekozen);」 –

+0

+1如果你不想有太多類,你甚至可以匿名實現 – Jerome

1

正如@Jesper所說,這是可能的反思,也許只有反思。反射是對象可以分析自身並遍歷其成員(屬性和方法)的過程。就你而言,你似乎在尋找一種方法。

通過你的代碼的外觀,它看起來像你想要的是,實際上,將一個函數對象傳遞給你的代碼,其中可以應用參數。這在Java中是不可能的。在Java 8中,類似的東西可能會增加閉包。你可以在Groovy中做到這一點,通過傳遞一個Closure作爲參數,或支持閉包或函數的其他語言。

你可以得到接近你想要通過定義一個抽象類/接口,通過它的一個實例,以你的方法,然後調用傳遞參數給它,就像一個方法是什麼:

interface Function <T> { 
    public Integer call(T t); 
} 


public class TestFunction { 
    static int intKiezer(Function<Integer> returnFunctie, String text) 
    { 
     int a = 10; 
     System.out.println(text); 

     return returnFunctie.call(a); 
    } 

    public static void main(String[] args) 
    { 
     Function<Integer> function = new Function<Integer>() { 
      public Integer call(Integer t) { return t * 2; } 
     }; 

     System.out.println(intKiezer(function, "Applying 10 on function")); 
    } 
} 

如果您意圖是調用一個方法,那麼你最好使用一些反射庫。想起了Apache Common's MethodUtil。我認爲這是你的男人:

invokeMethod(Object object, String methodName, Object arg) 
    Invoke a named method whose parameter type matches the object type. 
相關問題