[英]Java: Creating objects with variable type and calling methods on an object with variable name
[英]Java name Objects with a variable name
所以我正在为Minecraft制作一个插件。 它基本上是一个团队插件。 我需要做的是能够创建多个团队,但是我似乎无法弄清楚如何将对象名称更改为所选团队名称的球员。 这是我的意思:
if (l.equalsIgnoreCase("NewTeam")) {
teamName= args[0]; // This is the players chosen team name
Team newTeam = new Team(teamName, sender);
newTeam.addPlayer(sender);
由于这是一个服务器插件,因此必须处理多个团队,这意味着它正在创建许多团队对象,但所有对象都使用newTeam。 有谁知道我可以做的更好的方法吗? 谢谢。
您要搜索团队名称到团队对象的映射吗? 然后,您可以按照以下步骤进行操作:
Map<String,Team> teams = new TreeMap<String,Team>();
//Returns the team for 'teamName' or creates one, if it doesn't exist
public Team getTeam(String teamName)
{
Team team = teams.get(teamName);
if(team == null)
{
team = new Team(teamName,sender); //is 'sender' specific for a team??
teams.put(teamName,team);
}
return team;
}
我假设您正在使用Bukkit API,并且进一步说,这是在CommandExecutor的onCommand方法中完成的,所以这看起来应该是这样的:
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args){
if(cmd.getName().equalsIgnoreCase("newteam")){ //Make sure this is the right command
if(args.length == 0) //If the sender hasn't included a name...
sender.sendMessage("You need to include a team name!"); //Tell them they need to
else{ //Otherwise...
Team newTeam = new Team(args[0]); //Create a new team with the designated name
if(sender instanceof Player) //If the sender is a player (could be console)...
newTeam.addPlayer((Player) sender); //Add them to the team
/*
* Insert some code to save/store the newly created team here
*/
}
return true; //Return (for Bukkit's benefit)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.