Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import org.bukkit.Bukkit;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.SimpleCommandMap;
import org.bukkit.plugin.Plugin;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
/**
* A class for handling reflections with {@link PluginCommand} and {@link SimpleCommandMap}
*/
public class PluginCommandFactory {
/**
* Constructor of {@link PluginCommand}
*/
private static Constructor<PluginCommand> constructor;
/**
* Field to retrieve a {@link org.bukkit.command.SimpleCommandMap} from the {@link org.bukkit.plugin.PluginManager}
*/
private static Field commandMapField;
/**
* Creates a new instance of a plugin command
*
* @param name Name of the command
* @return The command
*/
public static PluginCommand create(String name, Plugin plugin) {
try {
return constructor.newInstance(name, plugin);
} catch (InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new RuntimeException(e);
}
}
/**
* Returns the {@link org.bukkit.command.CommandMap} that is specialized for plugin commands
*
* @return The command map
*/
public static SimpleCommandMap getCommandMap() {
try {
return (SimpleCommandMap) commandMapField.get(Bukkit.getPluginManager());
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
/**
* Registers the specified {@link PluginCommand}
*
* @param command Command to register
*/
public static void register(PluginCommand command) {
getCommandMap().register(command.getPlugin().getDescription().getName(), command);
}
static {
try {
constructor = PluginCommand.class.getDeclaredConstructor(String.class, Plugin.class);
constructor.setAccessible(true);
commandMapField = Bukkit.getPluginManager().getClass().getDeclaredField("commandMap");
commandMapField.setAccessible(true);
} catch (NoSuchMethodException | NoSuchFieldException e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.