java 50 lines · 7 steps

Building an annotation-driven EventBus in Java

A publish-subscribe hub that discovers handlers via reflection and dispatches events by type, synchronously or asynchronously.

Explained by highlit
1public class EventBus {
2 
3 private final Map<Class<?>, List<Subscriber>> subscribers = new ConcurrentHashMap<>();
4 private final Executor executor;
5 
6 public EventBus(Executor executor) {
7 this.executor = executor;
8 }
9 
10 public void register(Object listener) {
11 for (Method method : listener.getClass().getDeclaredMethods()) {
12 Subscribe annotation = method.getAnnotation(Subscribe.class);
13 if (annotation == null) {
14 continue;
15 }
16 if (method.getParameterCount() != 1) {
17 throw new IllegalArgumentException(
18 "@Subscribe method " + method + " must accept exactly one argument");
19 }
20 method.setAccessible(true);
21 Class<?> eventType = method.getParameterTypes()[0];
22 subscribers.computeIfAbsent(eventType, key -> new CopyOnWriteArrayList<>())
23 .add(new Subscriber(listener, method, annotation.async()));
24 }
25 }
26 
27 public void post(Object event) {
28 List<Subscriber> targets = subscribers.get(event.getClass());
29 if (targets == null) {
30 return;
31 }
32 for (Subscriber subscriber : targets) {
33 if (subscriber.async) {
34 executor.execute(() -> subscriber.deliver(event));
35 } else {
36 subscriber.deliver(event);
37 }
38 }
39 }
40 
41 private record Subscriber(Object target, Method method, boolean async) {
42 void deliver(Object event) {
43 try {
44 method.invoke(target, event);
45 } catch (ReflectiveOperationException e) {
46 throw new IllegalStateException("Failed to dispatch " + event, e);
47 }
48 }
49 }
50}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Reflection plus a marker annotation lets you wire handlers by convention instead of explicit registration.
  2. 2Keying subscribers by event class turns dispatch into a simple type lookup.
  3. 3Concurrent collections and an Executor let the bus stay thread-safe while offloading async delivery.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building an annotation-driven EventBus in Java — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code