下面列出了怎么用org.bukkit.command.PluginCommand的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Unregisters a CommandExecutor with the server
*
* @param command the command instance
* @param <T> the command executor class type
* @return the command executor
*/
@Nonnull
public static <T extends CommandExecutor> T unregisterCommand(@Nonnull T command) {
CommandMap map = getCommandMap();
try {
//noinspection unchecked
Map<String, Command> knownCommands = (Map<String, Command>) KNOWN_COMMANDS_FIELD.get(map);
Iterator<Command> iterator = knownCommands.values().iterator();
while (iterator.hasNext()) {
Command cmd = iterator.next();
if (cmd instanceof PluginCommand) {
CommandExecutor executor = ((PluginCommand) cmd).getExecutor();
if (command == executor) {
cmd.unregister(map);
iterator.remove();
}
}
}
} catch (Exception e) {
throw new RuntimeException("Could not unregister command", e);
}
return command;
}
private PluginCommand setupBukkitCommand() {
try {
final Constructor<PluginCommand> c = PluginCommand.class.getDeclaredConstructor(String.class, Plugin.class);
c.setAccessible(true);
final PluginCommand bukkitCommand = c.newInstance(name, Skript.getInstance());
bukkitCommand.setAliases(aliases);
bukkitCommand.setDescription(description);
bukkitCommand.setLabel(label);
bukkitCommand.setPermission(permission);
// We can only set the message if it's simple (doesn't contains expressions)
if (permissionMessage.isSimple())
bukkitCommand.setPermissionMessage(permissionMessage.toString(null));
bukkitCommand.setUsage(usage);
bukkitCommand.setExecutor(this);
return bukkitCommand;
} catch (final Exception e) {
Skript.outdatedError(e);
throw new EmptyStacktraceException();
}
}
@Override
public void registerCommand(String commandName, CommandExecutor executor, String description, String usage, String... aliases) {
PluginCommand command = getCommand(commandName);
if(command == null) {
forceRegisterCommand(commandName, executor, description, usage, aliases);
return;
}
command.setExecutor(executor);
if(executor instanceof TabCompleter) {
TabCompleter completer = (TabCompleter) executor;
command.setTabCompleter(completer);
}
if(executor instanceof Listener) {
Listener listener = (Listener) executor;
PluginManager manager = Bukkit.getPluginManager();
manager.registerEvents(listener, this);
}
}
private PluginCommand createPluginCommand() {
plugin.debug("Creating plugin command");
try {
Constructor<PluginCommand> c = PluginCommand.class.getDeclaredConstructor(String.class, Plugin.class);
c.setAccessible(true);
PluginCommand cmd = c.newInstance(name, plugin);
cmd.setDescription("Manage players' shops or this plugin.");
cmd.setUsage("/" + name);
cmd.setExecutor(new ShopBaseCommandExecutor());
cmd.setTabCompleter(new ShopBaseTabCompleter());
return cmd;
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
plugin.getLogger().severe("Failed to create command");
plugin.debug("Failed to create plugin command");
plugin.debug(e);
}
return null;
}
/**
* Registers a command executor
*
* @param command command enum
* @param executor the executor
*/
public void registerExecutor(CommandWrapper command, CommandExecutor executor) {
if(!executors.containsKey(command)) {
executors.put(command, executor);
if(command.hasGenericCommand()) {
PluginCommand genericCommand = plugin.getCommand(command.getGenericCommand());
if(executor instanceof org.bukkit.command.CommandExecutor) {
genericCommand.setExecutor((org.bukkit.command.CommandExecutor) executor);
}
else {
genericCommand.setExecutor(genericExecutor);
}
}
command.setExecutor(executor);
}
}
@SneakyThrows
public static void addExecutor(Plugin plugin, Command command) {
Field f = SimplePluginManager.class.getDeclaredField("commandMap");
f.setAccessible(true);
CommandMap map = (CommandMap) f.get(plugin.getServer().getPluginManager());
Constructor<PluginCommand> init = PluginCommand.class.getDeclaredConstructor(String.class, Plugin.class);
init.setAccessible(true);
PluginCommand inject = init.newInstance(command.getName(), plugin);
inject.setExecutor((who, __, label, input) -> command.execute(who, label, input));
inject.setAliases(command.getAliases());
inject.setDescription(command.getDescription());
inject.setLabel(command.getLabel());
inject.setName(command.getName());
inject.setPermission(command.getPermission());
inject.setPermissionMessage(command.getPermissionMessage());
inject.setUsage(command.getUsage());
map.register(plugin.getName().toLowerCase(), inject);
}
private void loadcmds()
{
PluginCommand command;
try
{
Constructor<PluginCommand> ctor = PluginCommand.class.getDeclaredConstructor(String.class, Plugin.class);
ctor.setAccessible(true);
command = ctor.newInstance("bungeeperms", this);
}
catch (Exception e)
{
System.err.println("Failed to register BungeePerms command!");
e.printStackTrace();
return;
}
command.setExecutor(new CmdExec());
command.setAliases(conf.isAliasCommand() ? Arrays.asList("bp") : new ArrayList());
command.setPermission(null);
getCommandMap().register("bungeeperms", command);
}
/**
* Gets the command with the given name, specific to this plugin. Commands
* need to be registered in the {@link PluginDescriptionFile#getCommands()
* PluginDescriptionFile} to exist at runtime.
*
* @param name name or alias of the command
* @return the plugin command if found, otherwise null
*/
public PluginCommand getCommand(String name) {
String alias = name.toLowerCase(java.util.Locale.ENGLISH);
PluginCommand command = getServer().getPluginCommand(alias);
if (command == null || command.getPlugin() != this) {
command = getServer().getPluginCommand(description.getName().toLowerCase(java.util.Locale.ENGLISH) + ":" + alias);
}
if (command != null && command.getPlugin() == this) {
return command;
} else {
return null;
}
}
private void registerCommand() {
if(plugin == null)
return;
PluginCommand cmd = plugin.getCommand("hawk");
cmd.setExecutor(new HawkCommand(this));
cmd.setPermission(Hawk.BASE_PERMISSION + ".cmd");
if (messages.isSet("unknownCommandMsg"))
cmd.setPermissionMessage(ChatColor.translateAlternateColorCodes('&', messages.getString("unknownCommandMsg")));
else {
messages.set("unknownCommandMsg", "Unknown command. Type \"/help\" for help.");
cmd.setPermissionMessage(ChatColor.translateAlternateColorCodes('&', messages.getString("unknownCommandMsg")));
}
}
/**
* Registers a CommandExecutor with the server
*
* @param plugin the plugin instance
* @param command the command instance
* @param permission the command permission
* @param permissionMessage the message sent when the sender doesn't the required permission
* @param description the command description
* @param aliases the command aliases
* @param <T> the command executor class type
* @return the command executor
*/
@Nonnull
public static <T extends CommandExecutor> T registerCommand(@Nonnull Plugin plugin, @Nonnull T command, String permission, String permissionMessage, String description, @Nonnull String... aliases) {
Preconditions.checkArgument(aliases.length != 0, "No aliases");
for (String alias : aliases) {
try {
PluginCommand cmd = COMMAND_CONSTRUCTOR.newInstance(alias, plugin);
getCommandMap().register(plugin.getDescription().getName(), cmd);
getKnownCommandMap().put(plugin.getDescription().getName().toLowerCase() + ":" + alias.toLowerCase(), cmd);
getKnownCommandMap().put(alias.toLowerCase(), cmd);
cmd.setLabel(alias.toLowerCase());
if (permission != null) {
cmd.setPermission(permission);
if (permissionMessage != null) {
cmd.setPermissionMessage(permissionMessage);
}
}
if (description != null) {
cmd.setDescription(description);
}
cmd.setExecutor(command);
if (command instanceof TabCompleter) {
cmd.setTabCompleter((TabCompleter) command);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return command;
}
private void registerCommand(String commandName, CommandExecutor executor){
PluginCommand command = UhcCore.getPlugin().getCommand(commandName);
if (command == null){
Bukkit.getLogger().warning("[UhcCore] Failed to register " + commandName + " command!");
return;
}
command.setExecutor(executor);
}
private void setupCommands() {
// Register all the commands
Commands.register(cmd);
// Get the Spigot command
PluginCommand command = getCommand("chunk");
if (command != null) {
// Use our custom plugin executor
command.setExecutor(cmd);
// Set the tab completer so tab complete works with all the sub commands
command.setTabCompleter(new AutoTabCompletion(this));
}
}
private PluginCommand getCommand(String name, Plugin plugin) {
try {
Constructor<PluginCommand> constructor = PluginCommand.class.getDeclaredConstructor(String.class, Plugin.class);
constructor.setAccessible(true);
return constructor.newInstance(name, plugin);
} catch (IllegalAccessException | IllegalArgumentException | InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException ex) {
DiscordBot.getInstance().getLogger().severe("Exception getting command!");
ex.printStackTrace();
}
return null;
}
@Override
protected void registerCommands() {
PluginCommand command = this.bootstrap.getCommand("luckperms");
if (command == null) {
getLogger().severe("Unable to register /luckperms command with the server");
return;
}
if (isAsyncTabCompleteSupported()) {
this.commandManager = new BukkitAsyncCommandExecutor(this, command);
} else {
this.commandManager = new BukkitCommandExecutor(this, command);
}
this.commandManager.register();
// setup brigadier
if (isBrigadierSupported()) {
try {
LuckPermsBrigadier.register(this, command);
} catch (Exception e) {
if (!(e instanceof RuntimeException && e.getMessage().contains("not supported by the server"))) {
e.printStackTrace();
}
}
}
}
private void registerCommands() {
getCommand(getName()).setExecutor(new HelpCommand(this));
getCommand("ping").setExecutor(new PingCommand(this));
getCommand("stacktrace").setExecutor(new StackTraceCommand(this));
getCommand("thread").setExecutor(new ThreadCommand(this));
getCommand("tpshistory").setExecutor(new TPSCommand(this));
getCommand("mbean").setExecutor(new MbeanCommand(this));
getCommand("system").setExecutor(new SystemCommand(this));
getCommand("env").setExecutor(new EnvironmentCommand(this));
getCommand("monitor").setExecutor(new MonitorCommand(this));
getCommand("graph").setExecutor(new GraphCommand(this));
getCommand("native").setExecutor(new NativeCommand(this));
getCommand("vm").setExecutor(new VmCommand(this));
getCommand("tasks").setExecutor(new TasksCommand(this));
getCommand("heap").setExecutor(new HeapCommand(this));
getCommand("lagpage").setExecutor(new PaginationCommand(this));
getCommand("jfr").setExecutor(new FlightCommand(this));
getCommand("network").setExecutor(new NetworkCommand(this));
PluginCommand timing = getCommand("timing");
try {
//paper moved to class to package co.aikar.timings
Class.forName("co.aiker.timings.TimingsIdentifier");
timing.setExecutor(new PaperTimingsCommand(this));
} catch (ClassNotFoundException e) {
timing.setExecutor(new SpigotTimingsCommand(this));
}
}
@Override
public PluginCommand getPluginCommand(String name) {
Command command = commandMap.getCommand(name);
if (command instanceof PluginCommand) {
return (PluginCommand) command;
} else {
return null;
}
}
private void registerCommands() {
getCommand(getName()).setExecutor(new HelpCommand(this));
getCommand("ping").setExecutor(new PingCommand(this));
getCommand("stacktrace").setExecutor(new StackTraceCommand(this));
getCommand("thread").setExecutor(new ThreadCommand(this));
getCommand("tpshistory").setExecutor(new TPSCommand(this));
getCommand("mbean").setExecutor(new MbeanCommand(this));
getCommand("system").setExecutor(new SystemCommand(this));
getCommand("env").setExecutor(new EnvironmentCommand(this));
getCommand("monitor").setExecutor(new MonitorCommand(this));
getCommand("graph").setExecutor(new GraphCommand(this));
getCommand("native").setExecutor(new NativeCommand(this));
getCommand("vm").setExecutor(new VmCommand(this));
getCommand("tasks").setExecutor(new TasksCommand(this));
getCommand("heap").setExecutor(new HeapCommand(this));
getCommand("lagpage").setExecutor(new PaginationCommand(this));
getCommand("jfr").setExecutor(new FlightCommand(this));
getCommand("network").setExecutor(new NetworkCommand(this));
PluginCommand timing = getCommand("timing");
try {
//paper moved to class to package co.aikar.timings
Class.forName("co.aiker.timings.TimingsIdentifier");
timing.setExecutor(new PaperTimingsCommand(this));
} catch (ClassNotFoundException e) {
timing.setExecutor(new SpigotTimingsCommand(this));
}
}
/**
* Register a command through the framework.
*/
public static boolean register(JavaPlugin plugin, CommandFramework command) {
PluginCommand pluginCommand = plugin.getCommand(command.label);
if (pluginCommand == null) {
return false;
}
pluginCommand.setExecutor(command);
return true;
}
public SpleefCommandManager(final HeavySpleef plugin) {
service = new CommandManagerService(plugin.getPlugin(), plugin.getLogger(), new MessageBundle.MessageProvider() {
@Override
public String provide(String key, String[] args) {
String message = null;
switch (key) {
case "message-player_only":
message = i18n.getString(Messages.Command.PLAYER_ONLY);
break;
case "message-no_permission":
message = i18n.getString(Messages.Command.NO_PERMISSION);
break;
case "message-description_format":
message = i18n.getVarString(Messages.Command.DESCRIPTION_FORMAT)
.setVariable("description", args[0])
.toString();
break;
case "message-usage_format":
message = i18n.getVarString(Messages.Command.USAGE_FORMAT)
.setVariable("usage", args[0])
.toString();
break;
case "message-unknown_command":
message = i18n.getString(Messages.Command.UNKNOWN_COMMAND);
break;
default:
//Get the message by i18n
message = i18n.getString(key);
}
return message;
}
}, new BukkitPermissionChecker(), plugin);
PluginCommand spleefCommand = plugin.getPlugin().getCommand("spleef");
spleefCommand.setExecutor(service);
spleefCommand.setTabCompleter(service);
}
public void register(PluginCommand command) {
Objects.requireNonNull(command, "command");
command.setExecutor(this);
command.setTabCompleter(this);
}
public void onEnable() {
instance = this;
// Initializing Config
ConfigFile config = ConfigFile.getInstance();
config.setup();
if (config.getConfig().getBoolean("resource-pack.force-on-join"))
ResourcePackManager.setForceResourcePack();
// Initializing Data File
DataFile.getInstance().setup();
// Initializing Lang File and adding all entries
LangFile lang = LangFile.getInstance();
lang.setup();
String pluginName = "more_minecraft";
lang.addEntry(pluginName, "sword", "Sword");
lang.addEntry(pluginName, "axe", "Axe");
lang.addEntry(pluginName, "picakaxe", "Pickaxe");
lang.addEntry(pluginName, "spade", "Shovel");
lang.addEntry(pluginName, "hoe", "Hoe");
lang.addEntry(pluginName, "helmet", "Helmet");
lang.addEntry(pluginName, "chestplate", "Chestplate");
lang.addEntry(pluginName, "leggings", "Leggings");
lang.addEntry(pluginName, "boots", "Boots");
lang.addEntry(pluginName, "leather_helmet", "Cap");
lang.addEntry(pluginName, "leather_chestplate", "Tunic");
lang.addEntry(pluginName, "leather_leggings", "Pants");
lang.addEntry(pluginName, "leather_boots", "Boots");
lang.addEntry(pluginName, "when_in_head", "When in head:");
lang.addEntry(pluginName, "when_in_body", "When in body:");
lang.addEntry(pluginName, "when_in_legs", "When in legs:");
lang.addEntry(pluginName, "when_in_feet", "When in feet:");
lang.addEntry(pluginName, "when_in_main_hand", "When in main hand:");
lang.addEntry(pluginName, "when_in_off_hand", "When in off hand:");
lang.addEntry(pluginName, "attribute_generic_attack_speed", "Attack Speed");
lang.addEntry(pluginName, "attribute_generic_attack_damage", "Attack Damage");
lang.addEntry(pluginName, "attribute_armor", "Armor");
lang.addEntry(pluginName, "attribute_armor_toughness", "Armor Toughness");
lang.addEntry(pluginName, "attribute_generic_follow_range", "Follow Range");
lang.addEntry(pluginName, "attribute_generic_knockback_resistance", "Knockback Resistance");
lang.addEntry(pluginName, "attribute_generic_luck", "Luck");
lang.addEntry(pluginName, "attribute_generic_max_health", "Max Health");
lang.addEntry(pluginName, "attribute_generic_movement_speed", "Speed");
lang.addEntry(pluginName, "attribute_horse_jump_strength", "Horse Jump Strength");
lang.addEntry(pluginName, "attribute_zombie_spawn_reinforcements", "Zombie Spawn Reinforcements");
lang.addEntry(pluginName, "durability", "Durability:");
lang.addEntry(pluginName, "death_message", " using [CustomItem]");
lang.addEntry(pluginName, "resource_pack_kick",
"You must accept the resource pack in order to join the server! Click on the server once, then click edit and change Server Resource pack to True.");
lang.addEntry(pluginName, "item_durability_main_hand", "Item Durability in Main Hand: ");
lang.addEntry(pluginName, "item_durability_off_hand", "Item Durability in Off Hand: ");
lang.saveLang();
// Initialize Metrics
new Metrics(this);
// Registering listeners
for (Listener listener : Arrays.asList(new EnchantItem(), new Anvil(), new CraftingTable(), new BlockBreak(),
new CustomItemBlockBreak(), new EntityDamage(), new EntityDamageByPlayerUsingCustomItem(),
new PlayerCustomItemDamage(), new PlayerInteract(), new CustomItemPlayerInteract(),
new PlayerShearEntity(), new CustomItemShearEntity(), new PlayerFish(), new CustomItemFish(),
new BlockIgnite(), new CustomItemBlockIgnite(), new EntityShootBow(), new EntityShootCustomBow(),
new CustomShieldEntityDamageByEntity(), new EntityToggleGlide(), new CustomElytraPlayerToggleGlide(),
this, new ArrowFromCustomBowHit(), new PlayerDeath(), new DurabilityBar(), new FurnaceBurn(),
new CustomItemFurnaceBurn(), new ResourcePackListener(), new Experience(), new ArmorListener(),
new ArmorEquip(), new PlayerDropItem(), new PlayerDropCustomItem(), new PlayerPickupItem(),
new PlayerPickupCustomItem())) {
getServer().getPluginManager().registerEvents(listener, this);
}
// Commands
PluginCommand additions = getCommand("additions");
additions.setExecutor(new AdditionsCmd());
additions.setTabCompleter(new AdditionsTab());
// Check if the server has the methods I added to Spigot (anything newer than around the 6th of August 2018 should be good)
try {
Material.DIAMOND_BLOCK.isInteractable();
Material.DIAMOND_BLOCK.getHardness();
Material.DIAMOND_BLOCK.getBlastResistance();
} catch (NoSuchMethodError e) {
MaterialUtils.useNewMethods = false;
}
// Commented out - these are not ready yet. Works on Linux but still fighting
// for the rest of the OSes.
// Tools.loadAgentLibrary();
// new RuntimeTransformer(ItemStackTransformer.class,
// CraftItemStack_1_12_Transformer.class);
// After all plugins have been enabled
getServer().getScheduler().scheduleSyncDelayedTask(this, () -> load());
}
public PluginCommand getBukkitCommand() {
return bukkitCommand;
}
public void registerCommand(String... aliases) {
PluginCommand pluginCommand = getCommand(aliases[0], DiscordBot.getInstance());
pluginCommand.setAliases(Arrays.asList(aliases));
getCommandMap().register(DiscordBot.getInstance().getDescription().getName(), pluginCommand);
}
public BukkitCommandExecutor(LPBukkitPlugin plugin, PluginCommand command) {
super(plugin);
this.plugin = plugin;
this.command = command;
}
public BukkitAsyncCommandExecutor(LPBukkitPlugin plugin, PluginCommand command) {
super(plugin, command);
}
@Override
public PluginCommand getPluginCommand(String s) {
return null;
}
public PluginCommand getCommand() {
return pluginCommand;
}
/**
* Gets a {@link PluginCommand} with the given name or alias.
*
* @param name the name of the command to retrieve
* @return a plugin command if found, null otherwise
*/
public static PluginCommand getPluginCommand(String name) {
return server.getPluginCommand(name);
}