Jacob Macallan
Jacob Macallan

Reputation: 979

What is the purpose of a listener in Java?

I looked for this online, but couldn't find an adequate explanation to what it exactly does. What I saw was a Java Interface and it was passed as a parameter in another class as a "Listener". People added various listeners to a list and called them all through a single method.

I'm not sure why I would use it. Can someone care to explain?

This is my original help post where someone told me to use listeners.

Link

Upvotes: 18

Views: 67525

Answers (7)

Code Guru
Code Guru

Reputation: 15578

Servlet Listener is used for listening to events in a web container, such as when you create a session or place an attribute in a session or if you passivate and activate in another container, to subscribe to these events you can configure listener in web.xml, for example, HttpSessionListener.

Listeners get triggered for an actual physical request that can be attached to events in your app server .With listeners, you can track application-level, session-level, life-cycle changes, attribute changes etc.

You can monitor and react to events in a servlet's life cycle by defining listener objects whose methods get invoked when lifecycle events occur.

Here is the blog post for Servlet Listener http://array151.blogspot.in/2016/12/servlet-listener.html

Upvotes: 1

MartinCz
MartinCz

Reputation: 548

Listener is a common form of implementing the observer design patter in Java. This technique is also referred to as the callback, which is a term coming from the world of procedural languages.

Observers register themselves by the observable, which in turn calls back the observers whenever some event occurs or when they should be notified about something.

Many framework libraries play the role of the observable, e.g.:

  • You register yourself (i.e., your implementation of the listener interface) as a listener of incoming messages in a messaging middleware.
  • You register yourself as a listener of some changes made by the user in the operating system.
  • You register yourself as a listener of GUI events, such as a button was click on.

Example in Java code:

Part 1 - The observable entity

import java.util.LinkedList;
import java.util.List;

public class Observable {
    private List<Observer> observers;

    public Observable() {
        observers = new LinkedList<>();
    }

    public void addObsever(Observer observer) {
        observers.add(observer);
    }

    private  void notifyObservers(String whatHappened) {
        for (Observer observer : observers) {
            observer.onSomethingHappened(whatHappened);
        }
    }

    public void doSomeStuff() {
        // ...
        // Do some business logic here.
        // ...

        // Now we want to notify all the listeners about something.
        notifyObservers("We found it!");

        // ...
        // Do some business logic here
        // ...
    }
}

Part 2 - The observer/listener interface

public interface Observer {
    void onSomethingHappened(String whatHappened);
}

Part 3 - Basic implementation of the observer/listener interface

public class MyObserver implements Observer {
    @Override
    public void onSomethingHappened(String whatHappened) {
        System.out.println(whatHappened);
    }
}

Part 4 - Putting it all together

public class Main {
    public static void main(String[] args) {

        // Create the observable.
        Observable myObservable = new Observable();

        // Create the observers (aka listeners).
        Observer myObserverA = new MyObserver();
        Observer myObserverB = new MyObserver();

        // Register the observers (aka listeners).
        myObservable.addObsever(myObserverA);
        myObservable.addObsever(myObserverB);

        myObservable.doSomeStuff();

    }
} 

And the result on standard output will be:

We found it!
We found it!

Upvotes: 21

Hoopje
Hoopje

Reputation: 12932

This is part of a programming paradigm called event-driven programming. Objects send messages to other objects on certain occasions, for example when they change. This is used often in GUI programming. Each GUI widget is implemented by a class. When you want to handle e.g. mouse clicks from the user, you add a listener (also called event handler) to GUI widget. When the user clicks on the widget, the widget sends the event to the registered listener(s) so that the application can respond to the mouse click. This seperates the framework (the GUI widget class) and the application code. (In some GUI frameworks, such as Swing, you can add an arbitrary number of listeners to an object; in others, you can specify only one.)

Also in other areas event-driven programming is useful. You might want to observe an object (see Observer pattern). For example, a collection which supports this, might send an event if its contents change. If you need to perform some processing if this occurs, you can add yourself as a listener to this class. The alternative would be to call the post-processing every time you add an item to the collection, but this error-prone.

Upvotes: 6

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

In the code example that you linked the KillMonsterEventListener

public interface KillMonsterEventListener {
    void onKillMonster ();
}

provides a way for users of your API to tell you something like this:

Here is a piece of code. When a monster is killed, call it back. I will decide what to do.

This is a way for me to plug in my code at a specific point in your execution stream (specifically, at the point when a monster is killed). I can do something like this:

yourClass.addKillMonsterEventListener(
    new KillMonsterEventListener() {
        public onKillMonster() {
            System.out.println("A good monster is a dead monster!");
        }
    }
);

Somewhere else I could add another listener:

yourClass.addKillMonsterEventListener(
    new KillMonsterEventListener() {
        public onKillMonster() {
            monsterCount--;
        }
    }
);

When your code goes through the list of listeners on killing a monster, i.e.

for (KillMonsterEventListener listener : listeners) {
    listener.onKillMonster()
}

both my code snippets (i.e. the monsterCount-- and the printout) get executed. The nice thing about it is that your code is completely decoupled from mine: it has no idea what I am printing, what variable I am decrementing, and so on.

Upvotes: 24

jakubbialkowski
jakubbialkowski

Reputation: 1566

Listeners are used for notify about state changes. You can think about Listeners in most of time as Observers, so every time something interesting happen your listener will be called.

You can read more about patterns in Java on following websites:

http://www.journaldev.com/1739/observer-design-pattern-in-java-example-tutorial

http://www.developer.com/java/implementing-behavioral-patterns-in-java.html

Upvotes: 0

Sachin Tanna
Sachin Tanna

Reputation: 46

Listeners do some work when an event occurs. They are called as "Event Listeners". Events like click, hover etc.. For Example, we have ActionListener interface in Java. It calls actionPerformed() method when an event occurs. You can refer http://java.about.com/od/a/g/Actionlistener.htm for more info.

Upvotes: 0

Christopher Oezbek
Christopher Oezbek

Reputation: 26353

Use a listener to let other code inform you of "conditions"/"events". For instance a "mouse listener" could be called if the mouse would have been moved/clicked/dragged. It depends on your application why it provides for listeners.

Upvotes: 0

Related Questions