当以字符串形式给出方法名称时,如何调用 Java 方法?
如果我有两个变量:
Object obj;
String methodName = "getName";
在不知道 obj
的类的情况下,如何调用它的 methodName
标识的方法?
被调用的方法没有参数,并且有一个 String
返回值。 它是 Java bean 的 getter。。
If I have two variables:
Object obj;
String methodName = "getName";
Without knowing the class of obj
, how can I call the method identified by methodName
on it?
The method being called has no parameters, and a String
return value. It's a getter for a Java bean.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(23)
对于那些从非静态方法调用同一类中的方法的人,请参阅以下代码:
For those who are calling the method within the same class from a non-static method, see below codes:
假设您从同一类中的静态方法调用静态方法。 为此,您可以使用以下代码作为示例。
解释一下,由于我们不希望在这里执行真正的面向对象编程,因此避免创建不必要的对象,因此我们将利用
class
属性来调用getMethod().
然后我们将为
invoke()
方法传入null
,因为我们没有对象来执行此操作。最后,因为我们,程序员,知道我们期待一个整数,那么
我们将
invoke()
调用的返回值显式转换为整数。现在您可能想知道:“用 Java 进行所有这些非面向对象编程有什么意义呢?”
我的用例是用 Java 解决 Project Euler 问题。 我有一个包含所有解决方案的 Java 源文件,我想传递命令行参数来确定要运行哪个 Project Euler 问题。
Suppose you're invoking a static method from a static method within the same class. To do that, you can sample the following code.
To explain, since we're not looking to perform true object-oriented programming here, hence avoiding the creation of unnecessary objects, we will instead leverage the
class
property to invokegetMethod()
.Then we will pass in
null
for theinvoke()
method because we have no object to perform this operation upon.And finally, because we, the programmer, know that we are expecting an integer, then
we explicitly cast the return value of the
invoke()
invocation to an integer.Now you may wonder: "What even is the point of doing all this non-object oriented programming in Java?"
My use case was to solve Project Euler problems in Java. I have a single Java source file containing all the solutions, and I wanted to pass in command line arguments to determine which Project Euler problem to run.
对我来说,一个非常简单且万无一失的方法就是简单地创建一个方法调用者方法,如下所示:
然后当您需要调用该方法时,只需输入类似这样的内容
for me a pretty simple and fool proof way would be to simply make a method caller method like so:
then when you need to call the method simply put something like this
从臀部编码,它会是这样的:
参数标识您需要的非常具体的方法(如果有多个可用的重载,如果该方法没有参数,则仅给出
methodName
)。然后,您可以通过再次调用来调用该方法
,如果没有的话,请省略
.invoke
中的参数。 但是是的。 了解 Java 反射Coding from the hip, it would be something like:
The parameters identify the very specific method you need (if there are several overloaded available, if the method has no arguments, only give
methodName
).Then you invoke that method by calling
Again, leave out the arguments in
.invoke
, if you don't have any. But yeah. Read about Java Reflection使用反射中的 方法调用:
其中:
“class name”
是类的名称objectToInvokeOn
属于 Object 类型,是您要调用方法的对象“method name”
是您要调用的方法的名称parameterTypes
的类型为Class[]
并声明该方法采用的参数params
的类型为Object[]
并声明要传递给方法的参数Use method invocation from reflection:
Where:
"class name"
is the name of the classobjectToInvokeOn
is of type Object and is the object you want to invoke the method on"method name"
is the name of the method you want to callparameterTypes
is of typeClass[]
and declares the parameters the method takesparams
is of typeObject[]
and declares the parameters to be passed to the method对于那些想要 Java 7 中直接代码示例的人:
Dog
类:ReflectionDemo
类:输出:
Mishka 已经 3 岁了。
您可以通过以下方式调用带有参数的构造函数:
或者,您可以删除
并执行
建议阅读: 创建新的类实例
For those who want a straight-forward code example in Java 7:
Dog
class:ReflectionDemo
class:Output:
Mishka is 3 year(s) old.
You can invoke the constructor with parameters this way:
Alternatively, you can remove
and do
Suggested reading: Creating New Class Instances
可以像这样调用该方法。 还有更多的可能性(检查反射 api),但这是最简单的一种:
The method can be invoked like this. There are also more possibilities (check the reflection api), but this is the simplest one:
首先,不要。 避免这种代码。 它往往是非常糟糕的代码并且也不安全(请参阅安全编码指南的第 6 节
Java 编程语言,版本 2.0)。
如果必须这样做,请选择 java.beans 而不是反射。 Beans 封装了反射,允许相对安全和常规的访问。First, don't. Avoid this sort of code. It tends to be really bad code and insecure too (see section 6 of Secure Coding Guidelines for the
Java Programming Language, version 2.0).
If you must do it, prefer java.beans to reflection. Beans wraps reflection allowing relatively safe and conventional access.为了完成我同事的回答,您可能需要密切注意:
这是一个旧的 java1.4 代码,它考虑了这些要点:
To complete my colleague's answers, You might want to pay close attention to:
Here is an old java1.4 code which takes into account those points:
索引(更快)
您可以使用
FunctionalInterface
将方法保存在容器中以对其进行索引。 您可以使用数组容器通过数字调用它们,也可以使用哈希图通过字符串调用它们。 通过这个技巧,您可以索引您的方法以更快动态地调用它们。Lambda 语法
您还可以使用 lambda 语法:
Indexing (faster)
You can use
FunctionalInterface
to save methods in a container to index them. You can use array container to invoke them by numbers or hashmap to invoke them by strings. By this trick, you can index your methods to invoke them dynamically faster.Lambda syntax
You can also use lambda syntax:
如果您多次调用,您可以使用 Java 7 中引入的新方法句柄。这里我们让您的方法返回一个字符串:
If you do the call several times you can use the new method handles introduced in Java 7. Here we go for your method returning a String:
这听起来像是可以通过 Java Reflection 包实现的事情。
http://java.sun.com/developer/technicalArticles/ALT/Reflection /index.html
特别是在按名称调用方法:
import java.lang.reflect.*;
This sounds like something that is doable with the Java Reflection package.
http://java.sun.com/developer/technicalArticles/ALT/Reflection/index.html
Particularly under Invoking Methods by Name:
import java.lang.reflect.*;
以下是准备使用的方法:
调用不带参数的方法:
调用带参数的方法:
使用上述方法如下:
输出:
Here are the READY TO USE METHODS:
To invoke a method, without Arguments:
To invoke a method, with Arguments:
Use the above methods as below:
Output:
SomeClass
是类,someVariable
是变量。SomeClass
is the class andsomeVariable
is a variable.请参考以下代码可能对您有帮助。
谢谢....
Please refer following code may help you.
Thanks....
Student.java
StudentTest.java
Student.java
StudentTest.java
您应该使用反射 - 初始化一个类对象,然后初始化此类中的方法,然后使用可选参数在对象上调用此方法。 请记住将以下代码片段包装在 try-catch 块中
希望它有帮助!
You should use reflection - init a class object, then a method in this class, and then invoke this method on an object with optional parameters. Remember to wrap the following snippet in try-catch block
Hope it helps!
这对我来说工作正常:
}
输出:
My input testparam
我可以通过将其名称传递给另一个方法(如 main)来调用该方法。
This is working fine for me :
}
Output:
My input testparam
I am able to invoke the method by passing its name to another method (like main).
使用
import java.lang.reflect.*;
以下是使用方法:
using
import java.lang.reflect.*;
and here is how you use it:
使用 jooR 它只是:
这是一个更详细的示例:
这会打印:
With jooR it's merely:
Here is a more elaborate example:
This prints: