Skip to content

Instantly share code, notes, and snippets.

@Goldmensch
Last active May 16, 2022 10:34
Show Gist options
  • Save Goldmensch/0fda51869bfbe0c8b9c560ddece56bf5 to your computer and use it in GitHub Desktop.
Save Goldmensch/0fda51869bfbe0c8b9c560ddece56bf5 to your computer and use it in GitHub Desktop.
a class to register a command without plugin.yml
package ###;
import org.bukkit.Bukkit;
import org.bukkit.command.*;
import org.bukkit.command.defaults.BukkitCommand;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
public class DCommand extends BukkitCommand {
private CommandExecutor commandExecutor;
private TabCompleter tabCompleter;
protected DCommand(@NotNull String name, CommandExecutor executor, TabCompleter tabCompleter) {
super(name);
setExecutor(executor);
setTabCompleter(tabCompleter);
}
protected DCommand(@NotNull String name) {
super(name);
}
public void setExecutor(CommandExecutor executor) {
commandExecutor = executor;
}
public void setTabCompleter(TabCompleter completer) {
tabCompleter = completer;
}
@Override
public @Nullable List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, String[] args) {
return tabCompleter != null ? tabCompleter.onTabComplete(sender, this, alias, args) : null;
}
@Override
public boolean execute(@NotNull CommandSender sender, @NotNull String commandLabel, @NotNull String[] args) {
return commandExecutor.onCommand(sender, this, commandLabel, args);
}
public void setProperties(Map<String, Object> properties) {
for(Map.Entry<String, Object> c : properties.entrySet()) {
setProperty(c.getKey(), c.getValue());
}
}
public void setProperty(String name, Object value) {
switch (name) {
case "aliases":
@SuppressWarnings("unchecked") List<String> aliases = (List<String>) value;
this.setAliases(aliases);
break;
case "usage":
this.setUsage((String) value);
break;
case "description":
this.setDescription((String) value);
break;
case "permission":
this.setPermission((String) value);
break;
}
}
public void register() {
if(commandExecutor == null) {
throw new CommandNotPreparedException();
}
try {
final Field bukkitCommandMap = Bukkit.getServer().getClass().getDeclaredField("commandMap");
bukkitCommandMap.setAccessible(true);
CommandMap commandMap = (CommandMap) bukkitCommandMap.get(Bukkit.getServer());
commandMap.register(getName(), this);
}catch (IllegalAccessException | NoSuchFieldException e) {
e.printStackTrace();
}
}
@SuppressWarnings("serial")
public static class CommandNotPreparedException extends RuntimeException{
public CommandNotPreparedException() {
super("no CommandExecutor was found");
}
}
}
@MarcusSlover
Copy link

How would you unregister a specific command?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment