Java动态函数调用 [英] Java dynamic function calling
问题描述
我有一个String数组,其中包含 yyyyyy
类中方法的名称
I have a String array that contains names of method in the yyyyyy
class
在<$ c中$ c> xxxxxx 我正在制作一个 yyyyyy
实例(比如 obj
)。现在我可以调用 obj.function_name()
,除了我想从循环中的String数组中读取 function_name
。这可能吗?
In the xxxxxx
class I'm making a yyyyyy
instance (say obj
). Now I can call obj.function_name()
, except I want to read function_name
from the String array in a loop. Is this possible?
推荐答案
你可以使用反射。它是通过调用 Yyyy.class.getMethod(methodName)来完成的.invoke(someArgs)
You can, using reflection. It is done by calling Yyyy.class.getMethod("methodName").invoke(someArgs)
你' d必须处理一堆异常,你的方法必须是 public
。请注意,java编码约定更喜欢 methodName
到 method_name
。
You'd have to handle a bunch of exceptions, and your method must be public
. Note that java coding conventions prefer methodName
to method_name
.
然而,使用反射应该是最后的选择。你应该使用更多面向对象的技术。
Using reflection, however, should be a last resort. You should be using more object-oriented techniques.
如果你经常需要类似的功能,也许你可以看看在java平台上运行的一些动态语言,比如 groovy
If you constantly need similar features, perhaps you can look at some dynamic language running on the java platform, like groovy
这篇关于Java动态函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!