Search code examples
javaeventsbukkit

Pass .class as parameter in method (JAVA) (BUKKIT/SPIGOT) (CUSTOM EVENT SYSTEM)


I'm trying to rewrite Bukkit's event system, which may be used as follows:

Bukkit.getPluginManager().registerEvents(new Listener() {
     @EventHandler
     public void onEvent(PlayerJoinEvent e) {
          Player player = e.getPlayer();
          player.sendMessage("Welcome!");
     }
}, this);

However, this is time-consuming and takes time to write out. To improve my workflow (drastically), I am trying to rewrite this system into something much more viable and flexible.

Here is how my ideal formatting/method would be used:

EventBus.register(PlayerJoinEvent.class, e -> {
     Player player = e.getPlayer();
     player.sendMessage("Welcome!");
}, this);

Currently, I have this:

public static void register(Class<? extends Event> clazz, Consumer<Event> consumer, JavaPlugin plugin) {
     consumer.accept(clazz.newInstance());
     // Bukkit.getPluginManager().registerEvents(e, plugin); // ???

}

My theory is to create a more usable class that implements Listener as seen in the current usage example, so that I can instantiate it with a provided Consumer<Event>.

My issue is that I need to pass that PlayerJoinEvent.class as a parameter in public void onEvent(<here> e) {.

How can I make this work? There's a couple issues with it and I have no idea how I can turn this from concept to reality this time.

I have no idea where to go now, and I hope I provided enough information.


Solution

  • You can do so with Generics, with this you can have a "variable" of a type in a method.

    public static <T extends Event> void register(Class<T> clazz, Consumer<T> consumer, JavaPlugin plugin) {
         ...
    }