这是我的enum
:
public enum StaffRanks {
HELPER("helpers"),
MODERATOR("moderators"),
ADMINISTRATOR("administrators"),
DEVELOPER("developers"),
OWNER("owners");
private String name;
StaffRanks(String name) {
this.setName(name);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
这是我创建Multimap
:
public static Multimap<String, StaffRanks> staffMembers;
public static void fetchPlayerRanks() {
JsonParser parser = new JsonParser();
try {
Object obj = parser.parse(new FileReader(".\\Data\\staff_list.json"));
JsonObject staffList = (JsonObject) obj;
Type listType = new TypeToken<List<String>>() {
}.getType();
staffMembers = ArrayListMultimap.create();
for (StaffRanks rank : StaffRanks.values()) {
staffMembers.put(new Gson().fromJson(staffList.get(rank.getName()), listType), rank);
}
} catch (Exception e) {
e.printStackTrace();
}
}
这就是我想要的方式:
int index = 39550;
for (String player : allStaffNames) {
onlineStatus = "@red@Offline";
if (onlineStaff.contains(PlayerHandler.getPlayer(player))) {
onlineStatus = "@gre@Online";
}
if (staffMembers.containsKey(player)) {
playerClient.getPA().sendFrame126("[" + staffMembers.get(player).getName() + "]@cya@" + Misc.formatPlayerName(player) + ": ", index);
}
playerClient.getPA().sendFrame126(onlineStatus, index - 1);
index += 2;
}
现在,问题是:如何从Multimap
内的枚举中获取名称?
这是我尝试过的。但是,它没有用。
staffMembers.get(player).getName()
以下是Staff_list.json
文件的样子:
{
"owners":['chuck'],
"developers":['tyrant','stan'],
"serverManagers":['logical'],
"staffManagers":['bench press', 'bench press2'],
"communityManagers":['cleave'],
"administrators":['zeven', 'reavers', 'redaeran', 'stuart'],
"moderators":['searwen', 'potentials', 'maud', 'lickylicky'],
"helpers":['megafun12', 'rhysj', 'vaping', 'punch']
}
答案 0 :(得分:0)
由于staffMembers
被定义为Multimap<String, StaffRanks>
,这意味着你应该将此作为Map<String, Collection<StaffRanks>>
阅读,并附带闪亮的Guava界面(例如,将键映射到集合 of values)。因此,在您的情况下,您实际上要做的是:
Collection<StaffRanks> staffRanksForPlayer = staffMembers.get(player);
staffRanksForPlayer.getName(); // BOOM!
如果您阅读/附加了错误消息,则会更容易。无论如何,你有两个选择:
Map<String, StaffRank>
- 如果是,请将收藏集更改为Map
并且您已经恢复正常。您必须以某种方式找到匹配的排名或在您的代码中使用所有这些排名。例如,后者可以用Java 8实现:
List<String> staffRanksNamesForPlayer = staffMembers.get(player).stream()
.map(StaffRanks::getName)
.collect(Collectors.toList());
// use list's `toString()` in your code to print its contents
playerClient.getPA().sendFrame126("[" + staffRanksNamesForPlayer.toString()
+ "]@cya@" + Misc.formatPlayerName(player) + ": ", index);
还有一件事:通常您想要指定您正在使用的特定Multimap
界面:ListMultimap
或SetMultimap
。