【问题标题】:How to call Java function from string stored in a Variable [duplicate]如何从存储在变量中的字符串调用Java函数[重复]
【发布时间】:2011-03-03 13:56:14
【问题描述】:

可能重复:
Calling a method named “string” at runtime in Java and C

我需要能够调用一个函数,但函数名存储在一个变量中,这可能吗?例如:

public void foo ()
{
     //code here
}

public void bar ()
{
     //code here
}

String functionName = "foo";

//我需要根据functionName来调用函数

任何帮助都会很棒,谢谢

【问题讨论】:

  • 如果您解释您认为需要这样做的原因,我们或许可以提供替代方案。

标签: java reflection function-call


【解决方案1】:

是的,你可以,使用反射。但是,也请考虑Effective Java 2nd Edition,Item 53:Prefer interfaces to reflection。如果可能,请改用接口。在一般应用程序代码中很少真正需要反射。

另见

相关问题

【讨论】:

    【解决方案2】:

    通过反射轻松完成。一些例子herehere

    代码的主要部分是

    String aMethod = "myMethod";
    
    Object iClass = thisClass.newInstance();
    // get the method
    Method thisMethod = thisClass.getDeclaredMethod(aMethod, params);
    // call the method
    thisMethod.invoke(iClass, paramsObj);
    

    【讨论】:

      【解决方案3】:

      使用反射。

      这是example

      【讨论】:

        【解决方案4】:

        使用reflection API。像这样的:

            Method method = getClass().getDeclaredMethod(functionName);
            method.invoke(this);
        

        【讨论】:

          猜你喜欢
          • 2012-05-17
          • 2015-05-20
          • 2017-07-02
          • 2011-04-27
          • 1970-01-01
          • 2013-01-03
          • 1970-01-01
          • 1970-01-01
          • 2018-06-21
          相关资源
          最近更新 更多