Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate of C# Events in Java

Tags:

I am .Net developer. i want to know that is there any event handling mechanism in Java for Events Handling like C#.

what i want to do is i want to raise/fire an event form my class upon some condition. and consumer of this class should register that event and write event handling method.

this can be done easily in C#. i have to implement this thing in Java.

after googling out i found some links but all those are talking about GUI events in AWT and swing.

can any one help me out.

like image 541
Mohsan Avatar asked Oct 07 '09 09:10

Mohsan


2 Answers

Although most of the examples will be to do with GUI events, the principles are basically the same. You basically want an interface or abstract class to represent a handler for the event, e.g.

public interface EventHandler
{
    // Change signature as appropriate of course
    void handleEvent(Object sender, EventArgs e);
}

then the publisher of the event would have:

public void addEventHandler(EventHandler handler)
public void removeEventHandler(EventHandler handler)

It would either keep a list of event handlers itself, or possibly have them encapsulated in a reusable type. Then when the event occurs, you just call handleEvent in each handler in turn.

You can think of delegate types in C# as being very similar to single-method interfaces in Java, and events are really just an add/remove pair of methods.

like image 123
Jon Skeet Avatar answered Oct 07 '22 12:10

Jon Skeet


I love C# Events,

They are simple to use and convenient. i missed them in java so wrote a small utility class that mimics the very basics of C# Event.

  • using java 8 (for lambdas)
  • no += operator, instead call .addListener((x) -> ...)
  • to trigger an event, call .broadcast(<EventArgs insance>)

Online Demo - https://repl.it/DvEo/2


Event.java

import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;

public class Event {
    private Set<Consumer<EventArgs>> listeners = new HashSet();

    public void addListener(Consumer<EventArgs> listener) {
        listeners.add(listener);
    }

    public void broadcast(EventArgs args) {
        listeners.forEach(x -> x.accept(args));
    }
}
  • You may want com.google.common.collect.Sets.newConcurrentHashSet() for thread safety

EventArgs.java

public class EventArgs {
}
like image 43
Jossef Harush Kadouri Avatar answered Oct 07 '22 12:10

Jossef Harush Kadouri