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).
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
Stringsto 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 ofButtonClickHandlerwhich will use the static methodonButtonTwoClick()to process the click of the button.