CommandHandler

Discussion in 'Spigot Plugin Development' started by Tanacious, Apr 22, 2017.

  1. I'm looking to create a CommandHandler for all the commands in a particular package.
    I can't seem to register all these commands through getCommand() by using a for statement to find all the classes in a package. I need help, and don't know where to go.

    I just need some pointers and maybe a tiny bit of code, no babying please.

    If I could use an @interface to do this that be great.
     
  2. Can you create a private method in your main class that loads all of your commands, then call it from onEnable?

    Code (Text):
    public void onEnable() {
        getCommands();
    }
    private void getCommands() {
    this.getCommand(command1).setExecutor(new class1(this));
    this.getCommand(command2).setExecutor(new class2(this));
    this.getCommand(command3).setExecutor(new class3(this));
    }
     
  3. You know this works too, right? You don't need to create a pointless method.
    Code (Text):
    public void onEnable() {
            this.getCommand("cmd"). setExecutor (new YourClass());
            this.getCommand("cmd2"). setExecutor(new YourClass());
    }
     
    • Agree Agree x 1
  4. Well, if you'd like to scan a package, I'd recommend Reflections, but that I won't help with here.
    Neither will I help with non-plugin.yml registration.

    To simply do this with an annotation, make one like this:
    Code (Java):
    @interface Cmd {
        String name();
        // more data you want.
    }
    Now add all the instances of the commands to an array like this:
    Code (Java):
    CommandExecutor executors[] = {new Executor1(), new Executor2()};
    To now register them, use this:
    Code (Java):
    for (CommandExecutor exec : executors) {
        Cmd anno = exec.getClass().getAnnotation(anno);
        if (anno == null) continue;
        getCommand(anno.name()).setExecutor(exec);
    }
    You can combine this method with Guice if you wish by using an array of Class<? implements CommandExecutor> and pass that into an injector.
     
    • Like Like x 1
  5. Of course, but my suggestion was so that the OP could load his many commands in a way that seems better on the eye. If you have a ton of commands you'd like to load, you don't have to overpopulate an onEnable method.
     
  6. This is what I want. Everyone else here who posted then said they were right, read my original post ffs.