簡體   English   中英

從字符串數組(Java或Groovy)調用函數

[英]Call a function from a string array (Java or Groovy)

在Java或Groovy中,假設我有一個像String這樣的String數組

myArray = ["SA1", "SA2", "SA3", "SA4"]

我想根據每個字符串調用不同的函數。

class Myclass{
  public static void SA1() {
    //doMyStuff
  }
  public static void SA2() {
    //doMyStuff
  }
  ...etc
}

我希望能夠遍歷我的數組並調用它們所屬的函數,而無需比較字符串或創建case語句。 例如,有沒有辦法做類似下面的事情,我知道它目前不起作用:

Myclass[myArray[0]]();

或者,如果您有其他方式的建議,我可以構建類似的東西。

在groovy你可以做:

Myclass.(myArray[0])()

在Java中,您可以:

MyClass.class.getMethod(myArray[0]).invoke(null);

在Groovy中,您可以使用GString進行動態方法調用:

myArray.each {
  println Myclass."$it"()
}

例如,您可以聲明一個接口,例如:

public interface Processor
{
    void process(String arg);
}

然后實現這個界面,例如在單身人士中。

然后創建一個Map<String, Processor> ,其中鍵是你的字符串,值是實現,並且在調用時:

Processor p = theMap.containsKey(theString)
    ? theMap.get(theString)
    : defaultProcessor;

p.process(theString);

我建議你看一下Reflection API,在運行時調用方法檢查Reflection文檔

Class cl = Class.forName("/* your class */");
Object obj = cl.newInstance();

//call each method from the loop
Method method = cl.getDeclaredMethod("/* methodName */", params);
method.invoke(obj, null);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM