7

可能重复:
在 Java 和 C 中在运行时调用名为“string”的方法

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

public void foo ()
{
     //code here
}

public void bar ()
{
     //code here
}

String functionName = "foo";

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

Anyhelp会很棒,谢谢

4

4 回答 4

5

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

也可以看看

相关问题

于 2010-06-14T15:30:44.153 回答
3

通过反射轻松完成。这里这里的一些例子。

代码的主要部分是

String aMethod = "myMethod";

Object iClass = thisClass.newInstance();
// get the method
Method thisMethod = thisClass.getDeclaredMethod(aMethod, params);
// call the method
thisMethod.invoke(iClass, paramsObj);
于 2010-06-14T15:30:23.810 回答
1

使用反射。

这是一个例子

于 2010-06-14T15:30:10.877 回答
-1

使用反射API。像这样的东西:

    Method method = getClass().getDeclaredMethod(functionName);
    method.invoke(this);
于 2010-06-14T15:31:00.207 回答