Template
mirror of
https://github.com/LOOHP/Limbo.git
synced 2026-09-06 11:48:54 +00:00
Cache Event Methods, Polish Last PR
This commit is contained in:
@@ -3,33 +3,31 @@ package com.loohp.limbo.events;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
import com.loohp.limbo.plugins.LimboPlugin;
|
||||
|
||||
public class EventsManager {
|
||||
|
||||
private List<ListenerPair> listeners;
|
||||
private Map<Listener, RegisteredCachedListener> cachedListeners;
|
||||
|
||||
public EventsManager() {
|
||||
listeners = new ArrayList<>();
|
||||
cachedListeners = new ConcurrentHashMap<>();
|
||||
}
|
||||
|
||||
public <T extends Event> T callEvent(T event) {
|
||||
for (EventPriority priority : EventPriority.getPrioritiesInOrder()) {
|
||||
for (ListenerPair entry : listeners) {
|
||||
Listener listener = entry.listener;
|
||||
for (Method method : listener.getClass().getMethods()) {
|
||||
if (method.isAnnotationPresent(EventHandler.class)) {
|
||||
if (method.getAnnotation(EventHandler.class).priority().equals(priority)) {
|
||||
if (method.getParameterCount() == 1 && method.getParameterTypes()[0].equals(event.getClass())) {
|
||||
try {
|
||||
method.invoke(listener, event);
|
||||
} catch (Exception e) {
|
||||
System.err.println("Error while passing " + event.getClass().getCanonicalName() + " to the plugin \"" + entry.plugin.getName() + "\"");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
for (Entry<Listener, RegisteredCachedListener> entry : cachedListeners.entrySet()) {
|
||||
for (Method method : entry.getValue().getListeners(event.getClass(), priority)) {
|
||||
try {
|
||||
method.invoke(entry.getKey(), event);
|
||||
} catch (Exception e) {
|
||||
System.err.println("Error while passing " + event.getClass().getCanonicalName() + " to the plugin \"" + entry.getValue().getPlugin().getName() + "\"");
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -39,10 +37,18 @@ public class EventsManager {
|
||||
|
||||
public void registerEvents(LimboPlugin plugin, Listener listener) {
|
||||
listeners.add(new ListenerPair(plugin, listener));
|
||||
cachedListeners.put(listener, new RegisteredCachedListener(plugin, listener));
|
||||
}
|
||||
|
||||
public void unregisterAllListeners(LimboPlugin plugin) {
|
||||
listeners.removeIf(each -> each.plugin.equals(plugin));
|
||||
listeners.removeIf(each -> {
|
||||
if (each.plugin.equals(plugin)) {
|
||||
cachedListeners.remove(each.listener);
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
protected static class ListenerPair {
|
||||
|
||||
Reference in New Issue
Block a user