Last active
February 4, 2025 14:49
-
-
Save ozanaaslan/291403239c87a336c1f4ac23e0d77e9e to your computer and use it in GitHub Desktop.
Lightweight event handling in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class EventManager { | |
| private final List<RegisteredListener> eventRegister = new ArrayList<>(); | |
| /** | |
| * Dispatches an event to all registered listeners. | |
| */ | |
| public <T extends Event> T dispatch(T event) { | |
| for (RegisteredListener registeredListener : eventRegister) { | |
| registeredListener.invoke(event); | |
| } | |
| return event; | |
| } | |
| /** | |
| * Registers all event-handling methods in a given listener instance. | |
| */ | |
| @SneakyThrows | |
| public void register(Class<?> listenerClass) { | |
| this.eventRegister.add(new RegisteredListener(listenerClass)); | |
| } | |
| /** | |
| * Inner class that holds listener references and invokes event methods. | |
| */ | |
| private static class RegisteredListener { | |
| private final Object listener; | |
| RegisteredListener(Class<?> listenerClass) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException { | |
| this.listener = listenerClass.getDeclaredConstructor().newInstance(); | |
| } | |
| @SneakyThrows | |
| <T extends Event> void invoke(T event) { | |
| for (Method method : listener.getClass().getMethods()) { | |
| if (method.isAnnotationPresent(EventBus.class) && method.getParameterCount() == 1) { | |
| Class<?> paramType = method.getParameterTypes()[0]; | |
| if (paramType.isAssignableFrom(event.getClass())) | |
| method.invoke(listener, event); | |
| } | |
| } | |
| } | |
| } | |
| @Target({ElementType.METHOD}) | |
| @Retention(RetentionPolicy.RUNTIME) | |
| public @interface EventBus { | |
| } | |
| public abstract static class Event { | |
| @Getter @Setter | |
| private boolean cancelled; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment