我想创建一个Message枚举,每个消息都在枚举类型上,以避免错误与消息键中的拼写错误.我还想使用参数(如#{0})来插入名称和更多信息.为了使事情变得更容易,我想添加方法get,该方法具有动态数量的(字符串类型)参数 - 每个我想要替换的参数都有一个.参数的确切数量应在编译时设置,并由该枚举值的字段定义.
考虑一下这个枚举:
public enum Message {
// Written by hand, ignore typos or other errors which make it not compile.
NO_PERMISSION("no_permission", 0),
YOU_DIED("you_died", 1),
PLAYER_LEFT("player_left", 2);
private String key;
private int argAmount;
Message(String key, int argAmount) {
this.key = key;
this.argAmount = argAmount;
}
public String replace(String... args) {
String message = get();
for (int i = 0; i < args.length; i++) {
message.replace("#{" + i + "}", args[i]);
}
return message;
}
public …Run Code Online (Sandbox Code Playgroud)