Search code examples
javaminecraftbukkit

Initialize a command in Spigot


I'm learning Spigot and many tutorials say to use this syntax to initialize a command.

    private Main plugin;

public Constructor(Main plugin) {
    this.plugin = plugin;
    plugin.getCommand("command").setExecutor(this);
}

But my Java knowledge is telling me that this would work as well.

    public Command(Main plugin) {
    plugin.getCommand("command").setExecutor(this);
}

Is there any difference between the two? Why would one be better to use than the other? Please don't answer with preferences, only pros and cons, or if they do the same thing.


Solution

  • I guess those names are just placeholders? Than: yes both will work. I would still recommend you the upper one. Most of the time you will have a lot of data manager classes e.g. a PlayerManager storing your custom player data. You could of course make everything static inside the Manager or make it a singleton, but it's better to initialize it in the on enable method to allow '/reload' to work properly and because you would probably want to inject the main there too. Back to why store the main. If you got your main stored in the command you can e.g. simply do 'main.getPlayerManager()' and don't have to use any static work arounds.

    There is also another way of injecting commands. You could add the command via reflection into the command map, which would not require you to.define the command in the plugin.yml.