Using PlayerCommandPreprocessEvent and java.lang.reflect
-
22-06-2021 - |
Question
I'm currently using PlayerCommandPreprocessEvent
.
I use syntax like this:
@EventHandler(priority = EventPriority.HIGHEST)
public void PlayerCommandPreprocess(PlayerCommandPreprocessEvent event){
String cmd;
String args;
if(event.getMessage().indexOf(" ") == -1){
cmd = event.getMessage().substring(1);
args = "";
getLogger().info(String.format("%s used '%s'",event.getPlayer().getDisplayName(), cmd));
}else{
cmd = event.getMessage().substring(0, event.getMessage().indexOf(" ")).substring(1);
args = event.getMessage().substring(event.getMessage().indexOf(" ")+1);
getLogger().info(String.format("%s used '%s' with args '%s'",event.getPlayer().getDisplayName(), cmd, args));
}
switch(cmd){
case "serverinfo":
event.getPlayer().sendMessage("This server is running some sort of new plugin that is not finished yet.");
event.setCancelled(true);
break;
case "spawn":
event.getPlayer().sendMessage("So you wanted to teleport to spawn to save time, right?");
event.getPlayer().sendMessage("This will teach you, cheater!");
event.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.POISON,1200,1));
event.setCancelled(true);
break;
default:
event.setCancelled(false);
break;
}
}
I would like to use separate methods inside of class PlayerCommands
.
As this will be the only plugin used on the server, I want to capture all commands, evaluate whether they have its PlayerCommands.cmd_<cmdname>()
and invoke it.
I know this is possible to do via java.lang.reflect
but right now I just don't know how to implement it on a Bukkit server.
Solution
I just used Class.forName()
to iterate through the methods and register them.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow