Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Pros and Cons of Listeners vs Method invocation through Reflection

  1. #1
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    623
    Thanks
    0
    Thanked 112 Times in 97 Posts

    Default Pros and Cons of Listeners vs Method invocation through Reflection

    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:
        public void init() {
            Button btn = new Button("some button");
            btn.addActionListener(new ActionListener() {
                public void onAction() {
                    doStuff();
                }
            });
        }
    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.

    Now, through the use of reflection we could do things like this:
        public void init() {
            Button btn = new Button("some button");
            btn.setAction(this, "doStuff");
        }
    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)


    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.
        public void setAction(Object source, String methodName) {
            this.source = source;
            this.method = source.getClass().getMethod(methodName, null);
        }
    (For simplicity, lets ignore exceptions for now)

    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.


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,307
    Thanks
    181
    Thanked 824 Times in 767 Posts
    Blog Entries
    5

    Default Re: Pros and Cons of Listeners vs Method invocation through Reflection

    The Listener approach is a standard design pattern called the Observer pattern (google it). The idea is that it creates a one-to-many relationship between an object and those that are supposed to be notified upon changes (or actions) of said object. This allows a programmer to write code such that it can respond in more ways than one to an action (or change), the responses can be reused in other contexts, and these responses can be added or removed at any time. The reflection approach you outlined suggests a one-to-one relationship, and if one wants a program to respond in multiple ways to a button action, one must jump through hoops (or write their own library) to do so. Another con of the reflection approach is that it can result in runtime errors (rather than compile time errors) that can deleteriously affect functionality.

  3. #3
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,669
    Thanks
    25
    Thanked 327 Times in 304 Posts

    Default Re: Pros and Cons of Listeners vs Method invocation through Reflection

    Copeg is spot on. Only use Reflection when absolutely necessary (there are cases, but they are rare). Reflection can lead to seemingly random and inconsistent runtime errors, which we all know is the most annoying things ever to debug. Notice the word "seemingly", because the exceptions thrown by Reflection are usually not immediately obvious that they are caused by code which uses Reflection.
    A general rule of thumb for programming: if you are going to use something that causes an error, make sure it consistently causes an error. An inconsistently thrown error can be extremely difficult to resolve because the first thing you should do when you get an error is find reliable reproduction steps. If you can't find steps which cause the problem 100% of the time, you often cannot resolve the issue, or you can never be sure that your solution truly worked.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  4. #4
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    623
    Thanks
    0
    Thanked 112 Times in 97 Posts

    Default Re: Pros and Cons of Listeners vs Method invocation through Reflection

    Quote Originally Posted by copeg View Post
    [...] This allows a programmer to write code such that it can respond in more ways than one to an action (or change), the responses can be reused in other contexts, and these responses can be added or removed at any time. The reflection approach you outlined suggests a one-to-one relationship, and if one wants a program to respond in multiple ways to a button action, one must jump through hoops (or write their own library) to do so.
    I dont see why this should be impossible with the Reflection approach. Sure, the example Code that I have shown is not the most fitting, but when designing an API you could easily work around that.
    One could create a little Wrapper class which remembers the source and the method to be invoked and have them in a list.


    Quote Originally Posted by copeg View Post
    Another con of the reflection approach is that it can result in runtime errors (rather than compile time errors) that can deleteriously affect functionality.
    Quote Originally Posted by aussiemcgr View Post
    [...] Reflection can lead to seemingly random and inconsistent runtime errors, which we all know is the most annoying things ever to debug. Notice the word "seemingly", because the exceptions thrown by Reflection are usually not immediately obvious that they are caused by code which uses Reflection.
    There is only 2 Exceptions which can be thrown by the Reflection methods used in this code; the NoSuchMethodException which is a fairly obvious one, and the SecurityException which is unlikely to happen unless the method is not public.
    The API says:
    SecurityException - If a security manager, s, is present and any of the following conditions is met:
    • invocation of s.checkMemberAccess(this, Member.PUBLIC) denies access to the method
    • the caller's class loader is not the same as or an ancestor of the class loader for the current class and invocation of s.checkPackageAccess() denies access to the package of this class
    Furthermore these are checked exceptions and their appearance is not at all random; if they will be thrown at all they will be thrown right at the initialization of the GUI.
    Maybe I am overlooking something, but from what I see I can not immediately agree with you there.

  5. #5
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,310
    My Mood
    Mellow
    Thanks
    194
    Thanked 669 Times in 656 Posts

    Default Re: Pros and Cons of Listeners vs Method invocation through Reflection

    You asked for pros and cons and got just that from 2 who apparently have relevant experience. They shared their thoughts, but I doubt they intend to argue with you.

  6. The Following User Says Thank You to GregBrannon For This Useful Post:

    copeg (January 11th, 2014)

  7. #6
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,307
    Thanks
    181
    Thanked 824 Times in 767 Posts
    Blog Entries
    5

    Default Re: Pros and Cons of Listeners vs Method invocation through Reflection

    Maybe I am overlooking something, but from what I see I can not immediately agree with you there.
    As Greg said - you asked for opinions and you got some. He's also correct in that I'm not going to argue the point - if you feel doing things through reflection is better then have at it - why not implement it by writing your own library doing so.

  8. #7
    Forum VIP
    Join Date
    Jun 2011
    Posts
    317
    My Mood
    Bored
    Thanks
    47
    Thanked 89 Times in 74 Posts
    Blog Entries
    4

    Default Re: Pros and Cons of Listeners vs Method invocation through Reflection

    Quote Originally Posted by Cornix
    I dont see why this should be impossible with the Reflection approach.
    It's not impossible, just a very bad idea. The most glaring problem is that you are substituting a trivial syntax error for run time exceptions. You are deliberately circumventing the compile time checks to save a few lines of code (which my IDE auto-generates anyway).

    The more subtle issue is the nature of reflection. It's a very powerful tool but also a very specific one. It's slow, unpredictable and difficult to test. It breaks encapsulation and doesn't fit in well with the OO paradigm.

    Don't get me wrong, Reflection can be awesome in the right places; error logging, serialization, plugins. It's just that I have attempted (and failed) to use it too many times to agree with you on any level. Learn to love Listeners.

  9. The Following User Says Thank You to ChristopherLowe For This Useful Post:

    copeg (January 11th, 2014)

  10. #8
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,669
    Thanks
    25
    Thanked 327 Times in 304 Posts

    Default Re: Pros and Cons of Listeners vs Method invocation through Reflection

    There is only 2 Exceptions which can be thrown by the Reflection methods used in this code; the NoSuchMethodException which is a fairly obvious one, and the SecurityException which is unlikely to happen unless the method is not public.

    Furthermore these are checked exceptions and their appearance is not at all random; if they will be thrown at all they will be thrown right at the initialization of the GUI.
    Um, no, no, and no.
    First, Class.getMethod() throws NoSuchMethodException, SecurityException, AND NullPointerException. And Method.invoke() throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NullPointerException, and ExceptionInInitializerError.
    Second, what your quote of the SecurityExceptions did not mention explicitly is that there is no guarantee the level of security required by the SecurityManager will be available on all environments (meaning, it might work for some, but might not work for others. Have fun debugging that).
    Third, the exceptions thrown by the invoke() method would happen when you call them which, according to your code, is when the user presses a button, not when the GUI starts up.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

Similar Threads

  1. Layering an application code: benefits and cons
    By angstrem in forum Java Theory & Questions
    Replies: 2
    Last Post: March 24th, 2013, 05:56 AM
  2. How to convert char to string by using method invocation?
    By Akirien in forum Object Oriented Programming
    Replies: 1
    Last Post: August 26th, 2012, 05:49 AM
  3. Method calls and Invocation
    By Akirien in forum Java Theory & Questions
    Replies: 1
    Last Post: August 24th, 2012, 01:37 PM
  4. Difference between RIM( Remote Methode Invocation) and WEB sever
    By ashish12169 in forum Java Theory & Questions
    Replies: 1
    Last Post: July 21st, 2012, 04:29 AM
  5. Action Listeners and Key Listeners Help
    By xctive in forum What's Wrong With My Code?
    Replies: 3
    Last Post: November 18th, 2010, 08:27 AM