Hi there.
First of all, this is a very theoretic question, there is a little wall of text ahead, I am sorry to take away so much of your precious time with this, but I would very much appreciate some opinions of more experienced programmers on this topic.
I know that the majority of standard java classes uses listeners when they are supposed to interact with application logic; for example AWT and Swing GUI components have listeners as a way to interact with the end user.
I personally have never really liked the listener approach in java because it forces you to write huge amounts of code for simple problems. At least thats my opinion.
If I have a GUI with a button, and, for example, and I want to invoke some method when the button is pressed I would have something like this in my initialization code:
Thats five lines of code, even when trying to make it somewhat small. I mean, I could always sprinkle in some white-lines to make it more friendly to the eyes, but I would not like to make it any smaller then this to keep it easily readable.public void init() { Button btn = new Button("some button"); btn.addActionListener(new ActionListener() { public void onAction() { doStuff(); } }); }
Now, through the use of reflection we could do things like this:
This would be much shorter with just a single line of code. It is also much more straight forward and easier to understand. (In my opinion)public void init() { Button btn = new Button("some button"); btn.setAction(this, "doStuff"); }
The button class would use Reflection to get an object of class Method which points to the Method doStuff within our Applications GUI initialization class.
(For simplicity, lets ignore exceptions for now)public void setAction(Object source, String methodName) { this.source = source; this.method = source.getClass().getMethod(methodName, null); }
When the button is pressed the internal logic would do something like this:
public void onPress() { this.method.invoke(source, null); }
Now both alternatives would obviously work. But I would like to know what the pros and cons would be, or what you would think they would be.
For example, would there be any major performance difference between both methods? Does one need significantly more ram? Might there be any compatibility issues that could come up in the future?
Just tell me anything you could think about.
Thank you all very much, I really appreciate any kind of input on this topic.