从字符串数组(Java或Groovy)调用函数 [英] Call a function from a string array (Java or Groovy)

查看:442
本文介绍了从字符串数组(Java或Groovy)调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java或Groovy中,假设我有一个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中,您可以这样做: b

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


In Java, or Groovy, say I have a String array like

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

I want to call a different function based off of each string.

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

I would love to be able to loop through my array and call the functions that they pertain to without having to compare the string or make a case statement. For example is there a way to do something like the following, I know it doesn't currently work:

Myclass[myArray[0]]();

Or if you have suggestions of another way I can structure something similar.

解决方案

In groovy you can do:

Myclass.(myArray[0])()

In Java you can do:

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

这篇关于从字符串数组(Java或Groovy)调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆