![](/img/trans.png)
[英]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.