Commands are built using a CommandDispatcher<S>, where <S> is your custom command source object. You build a command tree using a builder pattern.
Key concepts:
- Literal nodes: Created via
literal("name"), requiring the user to type a specific string. - Argument nodes: Created via
argument("name", type), which parse input into specific types (e.g., integer()). - Executes: An
.executes(context -> { ... }) block defines the action to take when the command reaches that node. - Subcommands: Created by chaining
.then() onto a node.
CommandDispatcher<CommandSourceStack> dispatcher = new CommandDispatcher<>();
dispatcher.register(
literal("foo")
.then(
argument("bar", integer())
.executes(c -> {
System.out.println("Bar is " + getInteger(c, "bar"));
return 1;
})
)
.executes(c -> {
System.out.println("Called foo with no arguments");
return 1;
})
);