如何从存储在变量中的字符串调用 Java 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3038464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:53:59  来源:igfitidea点击:

How to call Java function from string stored in a Variable

javareflectionfunction-call

提问by Lizard

Possible Duplicate:
Calling a method named “string” at runtime in Java and C

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

I need to be able to call a function, but the function name is stored in a variable, is this possible. e.g:

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

public void foo ()
{
     //code here
}

public void bar ()
{
     //code here
}

String functionName = "foo";

// i need to call the function based on what is functionName

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

Anyhelp would be great, thanks

Anyhelp会很棒,谢谢

采纳答案by polygenelubricants

Yes, you can, using reflection. However, consider also Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection. If at all possible, use interfaces instead. Reflection is rarely truly needed in general application code.

是的,你可以,使用反射。但是,也请考虑Effective Java 2nd Edition,第 53 条:首选接口而不是反射。如果可能,请改用接口。一般应用程序代码中很少真正需要反射。

See also

也可以看看

Related questions

相关问题

回答by patros

Use reflection.

使用反射。

Here's an example

这是一个例子

回答by Robin

Easily done with reflection. Some examples hereand here.

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

The main bits of code being

代码的主要部分是

String aMethod = "myMethod";

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

回答by unbeli

With the reflectionAPI. Something like this:

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

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