Skip to content

Instantly share code, notes, and snippets.

@Exerosis
Last active January 15, 2024 06:37
Show Gist options
  • Save Exerosis/c980daae799499d3f929bcf67f1502a9 to your computer and use it in GitHub Desktop.
Save Exerosis/c980daae799499d3f929bcf67f1502a9 to your computer and use it in GitHub Desktop.
A simpler and faster system for registering Bukkit event listeners in Java, Kotlin or Scala.
import org.bukkit.Bukkit;
import org.bukkit.event.Event;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.HandlerList;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.EventExecutor;
import java.util.function.Consumer;
public interface Events extends Listener, EventExecutor {
static <T extends Event> Events listen(
Plugin plugin,
Class<T> type,
Consumer<T> listener
) { return listen(plugin, type, EventPriority.NORMAL, listener); }
static <T extends Event> Events listen(
Plugin plugin,
Class<T> type,
EventPriority priority,
Consumer<T> listener
) {
final Events events = ($, event) -> listener.accept(type.cast(event));
Bukkit.getPluginManager().registerEvent(type, events, priority, events, plugin);
return events;
}
default void unregister() {
HandlerList.unregisterAll(this);
}
}
/* Usage Example
Events.listen(plugin, PlayerJoinEvent.class, event -> {
//Event code here.
});
*/
import org.bukkit.Bukkit
import org.bukkit.event.Event
import org.bukkit.event.EventPriority
import org.bukkit.event.HandlerList
import org.bukkit.event.Listener
import org.bukkit.plugin.EventExecutor
import org.bukkit.plugin.Plugin
class EventListener(private val listener: Event.() -> Unit) : EventExecutor, Listener {
override fun execute(ignored: Listener, event: Event) = listener(event)
fun unregister() = HandlerList.unregisterAll(this)
}
inline fun <reified T : Event> listen(
plugin: Plugin,
priority: EventPriority = EventPriority.NORMAL,
noinline listener: T.() -> Unit
) = EventListener(listener as Event.() -> Unit).also {
Bukkit.getPluginManager().registerEvent(T::class.java, it, priority, it, plugin)
}
import java.util.function.Consumer
import org.bukkit.Bukkit
import org.bukkit.event.{Event, EventPriority, HandlerList, Listener}
import org.bukkit.plugin.{EventExecutor, Plugin}
trait Events[E <: Event] extends Listener with EventExecutor {
def unregister(): Unit = HandlerList.unregisterAll(this)
}
object Events {
def listen[E <: Event](
plugin: Plugin,
listener: Consumer[E],
priority: EventPriority = EventPriority.NORMAL
): Events[E] = {
val events: Events[E] = (_, event: E) => listener(event)
Bukkit.getPluginManager.registerEvent(classOf[E], events, priority, events, plugin)
events
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment