Java (Spigot/Bukkit) multiple classes

118 Views Asked by At

I have my main class Main.java (onEnable method) and 3 others.

in Main.java I'm registering other classes so:

new Example(this);
new Shop(this);
new Info(this);

and in the classes themselves, I use this construction:

public class Shop implements Listener {

    private final JavaPlugin plugin;

    public Shop(JavaPlugin plugin) {
        this.plugin = plugin;
        plugin.getServer().getPluginManager().registerEvents(this, plugin);
}

The gist of the question: I read somewhere that you can avoid writing class registration in the main method (because it takes up a lot of space and makes the code unreadable) How to get rid of

new Example(this);
new Shop(this);
new Info(this);

I've tried plugin = this; But it's not working.

3

There are 3 best solutions below

2
lance-java On

Personally I'd do

public static void main(String[] args) {
   List<Listener> listeners = List.of(
      new Example(),
      new Shop(),
      new Info()
   );
   JavaPlugin plugin = new JavaPlugin(...);
   PluginManager pluginManager = plugin.getServer().getPluginManager();
   for (Listener listener : listeners) {
      pluginManager.registerEvents(listener, plugin);
   }
}
0
atlaska826 On

When I am creating my classes, I use the following code in each class I create to register it in the main method without having to add code there.

public class ClassName {
    Main plugin;

    public ClassName(Main plugin) {
        this.plugin = plugin;
    }
}

Example of the actual implementation of above code snippet: If you want to register your Listeners, you can add the following code in your onEnable() method.

getServer().getPluginManager().registerEvents(new YourListenerClassName(this), (Plugin) this);
0
kerudion On

Without using reflection, you can try something like this using static blocks:

Main.java

public class Main extends JavaPlugin {
    private static JavaPlugin plugin;

    @Override
    public void onEnable() {
        plugin = this;
    }

    public static void register(Listener listener) {
        plugin.getServer().getPluginManager().registerEvents(listener, plugin);
    }
}

MyListener.java

public class MyListener implements Listener {
    static {
        Main.register(new MyListener());
    }

    ...
}

and so on for all listeners.