Custom command class

Since 1.0.0

While the previous example shown on "Limiting access" under the "Commands" page works, it is definetively not the way I would recommend to create an specific group of commands that follow certain criteria. For that, I would use a custom MCCommand class, which is what we will do here.

The requirements

Our new MCCommand class will enforce the following requirements for the CommandSender executing or tab-completing any command that extends this class while trying to do that in an optimized way:

  • The command will only be useable by players, not the console

  • Players will be required to have a clan to use the command (We ignore clan creation)

So let's create the class, shall we?

import net.codersky.mcutils.general.MCCommand;
import net.codersky.clans.ClanPlugin;

public abstract class ClanCommand extends MCPlugin<ClanPlugin> {

    public ClanCommand(ClanPlugin plugin, String name) {
        super(plugin, name);
        // We are going to check for the sender class ourselves, for optimization.
    }

    // The two new methods that this command class will use, with the
    // sender already casted to Player and a Clan instance.

    public abstract boolean onCommand(Player sender, Clan clan, String[] args);
    
    public abstract List<String> onTab(Player sender, Clan clan, String[] args);

    // Override old methods to call the new ones with the new requirements.

    @Override
    public final boolean onCommand(CommandSender sender, String[] args) {
        if (!(sender instanceof Player))
            return getPlugin().getMessages().send(sender, "clan.noPlayer");
        Player player = (Player) sender;
        Clan clan = getPlugin().getClanManager().getClan(player);
        if (clan == null)
            return getPlugin().getMessages().send(player, "clan.noClan");
        return onCommand(player, clan, args);
    }

    @Override
    public final List<String> onTab(CommandSender sender, String[] args) {
        if (!(sender instanceof Player))
            return null;
        Player player = (Player) sender;
        Clan clan = getPlugin().getClanManager().getClan(player);
        if (clan == null)
            return null;
        return onTab(player, clan, args);
    }
}

And that's it, new commands extending this ClanCommand class will already have a casted Player and a Clan instance, additionally, they could also override the hasAccess method as we didn't use it for this class. Note that the old methods are marked as final so any class extending ClanCommand can't overide them and break the logic. We could of course add utility methods or shortcuts related to our new class, for example, a shortcut to that "clan manager", or even the getClan method itself.

Last updated