Alternate of C# Events in Java

后端 未结 4 1820
迷失自我
迷失自我 2020-12-24 02:55

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 even

4条回答
  •  天涯浪人
    2020-12-24 03:53

    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()

    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> listeners = new HashSet();
    
        public void addListener(Consumer 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 {
    }
    

提交回复
热议问题