How to Unregister Commands from your plugin.

Discussion in 'Resources' started by zeeveener, Feb 26, 2013.

Thread Status:
Not open for further replies.
  1. Offline


    Recently, I have been looking for a safe method to unregister commands as my plugin likes to take control over alot of other plugins...
    I looked high and low and finally found THIS POST which describes how to remove a command from Bukkit altogether. Unfortunately, whilst testing this, I ran into issues as it would remove the same command from other plugins as well.

    My alteration allows you to remove the command and it's aliases from your plugin only. Other plugins with the same aliases/commands will not be affected.

    1. private static Object getPrivateField(Object object, String field)throws SecurityException,
    2. Class<?> clazz = object.getClass();
    3. Field objectField = clazz.getDeclaredField(field);
    4. objectField.setAccessible(true);
    5. Object result = objectField.get(object);
    6. objectField.setAccessible(false);
    7. return result;
    8. }
    10. public static void unRegisterBukkitCommand(PluginCommand cmd) {
    11. try {
    12. Object result = getPrivateField(this.getServer().getPluginManager(), "commandMap");
    13. SimpleCommandMap commandMap = (SimpleCommandMap) result;
    14. Object map = getPrivateField(commandMap, "knownCommands");
    15. @SuppressWarnings("unchecked")
    16. HashMap<String, Command> knownCommands = (HashMap<String, Command>) map;
    17. knownCommands.remove(cmd.getName());
    18. for (String alias : cmd.getAliases()){
    19. if(knownCommands.containsKey(alias) && knownCommands.get(alias).toString().contains(this.getName())){
    20. knownCommands.remove(alias);
    21. }
    22. }
    23. } catch (Exception e) {
    24. e.printStackTrace();
    25. }
    26. }

    To call on this, you must first get the instance of the command you wish to unregister.
    1. PluginCommand cmd = this.getCommand("cmd");
    2. unRegisterBukkitCommand(cmd);

    That's all there is to it. If the command is already unregistered, or doesn't exist, there will be a NullPointerError. You can handle that however you want.

    Hopefully this helps.
    xize, HackintoshMan, Cirno and 4 others like this.
  2. Offline


    Reflection, fun!
    Thanks for this!
  3. Offline


    Thank you for this!

    Helping greatly in my new modular project!
  4. Offline


    Doesnt longer work :(
  5. Offline


    Jhtzb I made a class for adding the aliases of my alias plugin to the command map in order to make tab completion possible. You can look into that and use some of its code to unregister commands from other plugins ;)
    SirFaizdat likes this.
Thread Status:
Not open for further replies.

Share This Page