How To Unregister a PluginCommand from Bukkit.

Discussion in 'Resources' started by Dark_Balor, Aug 16, 2011.

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

    Dark_Balor

    Hi,
    For one of my plugin I searched a way to let the user disable some of the command and remove them from the bukkit CommandMap.

    Here is the way to achieve it :

    Code:java
    1.  
    2. /**
    3.   * Getting the private field of a another class;
    4.   *
    5.   * @param object
    6.   * @param field
    7.   * @return
    8.   * @throws SecurityException
    9.   * @throws NoSuchFieldException
    10.   * @throws IllegalArgumentException
    11.   * @throws IllegalAccessException
    12.   */
    13. private Object getPrivateField(Object object, String field) throws SecurityException,
    14. Class<?> clazz = object.getClass();
    15. Field objectField = clazz.getDeclaredField(field);
    16. objectField.setAccessible(true);
    17. Object result = objectField.get(object);
    18. objectField.setAccessible(false);
    19. return result;
    20. }
    21.  
    22. /**
    23.   * Unregister a command from bukkit.
    24.   *
    25.   * @param cmd
    26.   */
    27. private void unRegisterBukkitCommand(PluginCommand cmd) {
    28. try {
    29. Object result = getPrivateField(plugin.getServer().getPluginManager(), "commandMap");
    30. SimpleCommandMap commandMap = (SimpleCommandMap) result;
    31. Object map = getPrivateField(commandMap, "knownCommands");
    32. @SuppressWarnings("unchecked")
    33. HashMap<String, Command> knownCommands = (HashMap<String, Command>) map;
    34. knownCommands.remove(cmd.getName());
    35. for (String alias : cmd.getAliases())
    36. knownCommands.remove(alias);
    37. } catch (SecurityException e) {
    38. e.printStackTrace();
    39. e.printStackTrace();
    40. } catch (NoSuchFieldException e) {
    41. e.printStackTrace();
    42. } catch (IllegalAccessException e) {
    43. e.printStackTrace();
    44. }
    45. }
    46.  
     
    SpikeMeister likes this.
  2. Offline

    Styx Reborn

    Interesting.
     
  3. Offline

    VioVioCity

    Holy!? That worked! You solved an issue of mine that I've had for a couple weeks!
     
  4. Offline

    iffa

    He also did that 8 months ago. Very interesting.
     
    Neodork likes this.
Thread Status:
Not open for further replies.

Share This Page