如何在java中的函数名称和实际函数之间建立链接
我正在 netBeans 中构建一个带有多个工具栏的用户界面(手动编码,更灵活)。
我想做的是为每个按钮创建一个actionListener。我正在从 XML 中检索函数名称并将它们解析为字符串。我将在单独的类中编写这些函数的实现,但我的问题如下:
如何在函数名称和包含其名称的字符串之间建立链接?
示例:字符串为 Open()
,函数为 Open(someParameter)
,在定义类中将为 static void Open(param)
。
I am building a user interface in netBeans (coding by hand, more flexible) with multiple toolbars.
What I am trying to do is create an actionListener for each button. I am retrieving names of the functions from XML and parse them to string. I will write implementations for those functions in a separate class, but my problem is the following:
How do I make the link between the function name and the string containing it's name?
Example: String is Open()
, function will be Open(someParameter)
and in the definitions class there will be static void Open(param)
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,请考虑我对您从字符串解析动态按钮行为的想法的评论,这是一种错误的方法。但是,如果您仍然需要您所要求的内容,那么您需要的是 Reflection API。
下面是一个示例:
添加:
另一个选项是使用映射将这些
字符串
链接到方法,它比反射稍微漂亮一些,但仍然是一个混乱的设计。代码有点长,但从 Java 的角度来看,它比使用反射来完成任务要好得多(除非您有一些我不知道的特定要求)。它的工作原理如下:调用
callByName("onButtonTwoClick()")
后,它将获取ButtonClickHandler
的相应实例,该实例将使用静态方法onButtonTwoClick ()
来处理按钮的点击。First of all, consider my comment about your idea of dynamic button behavior resolved from strings being a wrong approach. However if you still need exactly what you asked, what you need is Reflection API.
Here's an example:
Added:
Another option, which is a little bit prettier than reflection, but still a messy design, would be to use a map to link those
Strings
to methods. The code is a bit longer, but from the Java perspective it is much better than using reflection for your task (unless you have some specific requirement of which I'm not aware). This is how it would work:After you call
callByName("onButtonTwoClick()")
it will fetch the respective instance ofButtonClickHandler
which will use the static methodonButtonTwoClick()
to process the click of the button.在我看来,您正在寻找 Java 中 JS“eval”函数的等效项。 这可能会有所帮助。尽管如此,正如 @Max 所说,这通常不是一个好主意,您可能需要重新考虑您的设计。
It seems to me that you are looking for the equivalent of JS "eval" function in Java. This might help. Nevertheless it is generally not a good idea as @Max stated, you might want to rethink your design.
如果我正确理解了您的问题,您将尝试根据从 XML 文件中获取的一些字符串来生成代码文件。我可以建议您使用这个库来生成代码。
有关教程,您可以访问此链接。
您甚至可以使用 Java Reflection API。这是教程的链接。
使用以上两者中的哪一个取决于您。
If i have understood your question correctly you are trying to generate your code files based on some strings taken from a XML file. I can suggest you this library to generate your codes.
For tutorials you can visit this link.
You may even use the Java Reflection API. Here is a link for the tutorial.
Its upto you, that which of the above two you use.