java - 从字符串Java的值调用函数

标签 java arrays reflection methods invoke

<分区>

Possible Duplicate:
How do I invoke a java method when given the method name as a string?

**我看过这个:Call a function from a string array (Java or Groovy)它对我不起作用,也许这是我的情况*

我有一个包含一些值的字符串数组,我希望能够调用一个方法,该方法是这些值之一,当然这可以改变,而且我可能有 100 个值,所以使用它是不可行的if/else if 构造,或 switch 语句。

有什么方法可以按照我的意愿调用该方法,如下面的代码所示?

private String[] = {"Hit","Slap","Blop"};
private String et = "Slap";

    public void Action(){

        for(int i = 0; i < arr.length;i++){
            if(et.equals(arr[i])){
                //Call method of that name ( Slap(); )

            }
        }   
    }

    public void Run(){
        ///
    }

    public void Slap(){
        ///
    }

    public void Blop(){
        ///
    }

编辑:我整合反射的尝试:

              for(int i = 0; i < arr.length;i++){
            if(et.equals(arr[i])){
                //Call method of that name
                 try {
                    method = this.getClass().getMethod(arr[i]);

                } catch (NoSuchMethodException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (SecurityException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                try {
                    return (String) method.invoke(this);
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }
        return "FAIL";

最佳答案

您将不得不使用反射。像这样:

getClass().getMethod(arr[i]).invoke(this);

关于java - 从字符串Java的值调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14429107/

相关文章:

java - 如何修复 "Exception raised during rendering: android.view.View cannot be cast to android.view.ViewGroup"

c++ - 比较数组c++中的项目

arrays - 如何在 for 循环中跟踪打印项目?

java - 在 Java 中加载已编译的类并从文件反序列化它的实例

java - 如何阻止 jackson 在 Spring MVC 中将日期写为时间戳

java - BIRT 变量 - 如何创建和使用?

c# - 如何存储类型 A 和运行时 Func<A,B> 类型转换之间的映射?

Java泛型和反射!

java - Spring MVC表单提交: view to controller pass not put form attribute

python - Numpy 将非连续数组的连续部分视为更大尺寸的 dtype