Skip to content

Creating your first subcommand

Leonardo Luiz Gava edited this page Jun 18, 2022 · 6 revisions

Subcommands are commands that are executed in a parent command through a parameter.

Creating subcommand class

GiveDiamondSubcommand class

public class GiveDiamondSubcommand extends NeelixSubcommand {
  public GiveDiamondSubcommand(String name, String permission) {
    super(name, permission);
  }

  @Override
  public void execute(Player player, String[] args) {
    player.getInventory().addItem(new ItemStack(Material.DIAMOND));
    player.sendMessage("You have been given a diamond!");
  }
}

Registering subcommands on parent command

main plugin class

public class MyPlugin extends JavaPlugin {

  @Override
  public void onEnable() {
    this.registerCommands();
  }

  private void registerCommands() {
    ArrayList<NeelixSubcommand> giveSubcommands = new ArrayList<>();
    giveSubcommands.add(new GiveDiamondSubcommand("1xDiamond", ""));

    this.getCommand("give").setExecutor(new NeelixCommandExecutor("give", giveSubcommands));
  }
} 

Commands with subcommands have auto tab complete.

Registering parent command

...
commands:
  give:
    description: A custom give command.
    usage: /<command>

Using subcommand as CommandExecutor

To avoid code repetition, you can convert your subcommand to a parent command with the toCommandExecutor() method.

main plugin class

public class MyPlugin extends JavaPlugin {

  @Override
  public void onEnable() {
    this.registerCommands();
  }

  private void registerCommands() {
    this.getCommand("gad").setExecutor(new GiveDiamondSubcommand().toCommandExecutor());
  }
} 

You don't need to pass any parameter to the subcommand constructor.
Don't forget to register the command on plugin.yml

...
commands:
  gad:
    description: Give a diamond to the sender.
    usage: /<command>