Хорошо, с вашим кодом много проблем. Сначала я дам вам прокомментированную версию вашего кода, показывающую все, что не так, а затем предоставлю версию, которая действительно работает. Вот ваш код:
public enum Msg { //should be called "Message", since it is in Message.java
//Common
Message1("this"),
Message2("is"),
Message3("not"),
Message4("cool"), //syntax error, the line should end in a semicolon (;)
private String message;
private static HashMap<Msg, String> Msgmap; //Msgmap is never initialized
private static HashMap<Msg, String> getMsgmap(){
return Msgmap;
}
Msg(String msg) { //again, should be named "Message", not "Msg"
this.message = msg;
if(getMsgmap() == null) { //this will always be true, because Msgmap is never initialized
setupMsgMap(); //this will run 4 times (once for every enum value)
}
}
private static void setupMessageMap() {
langmap = new HashMap<Lang, String>(); //syntax error (you didn't declare or infer a type), and the Lang class has not been provided to us, I assume you meant to use the Msg class instead
for(Lang lang:values()){ //NullPointerException occurs here. We're still initializing the first enum constant, but you're asking the compiler to loop through ALL the enum constants. They aren't initialized yet though; they don't actually exist yet.
langmap.put(lang, lang.lang);
}
}
}
Вот мой обновленный код:
public enum Message { //the class is named "Message"
Message1("this"),
Message2("is"),
Message3("not"),
Message4("cool"); //line ends in a semicolon
private String message;
private static HashMap<Message, String> Msgmap = new HashMap<>(); //Msgmap is initialized here
public static HashMap<Message, String> getMsgmap() {
return Msgmap;
}
Message(String msg) {
this.message = msg;
//I don't set up Msgmap in the constructor, because it is still initializing itself here, so we can't possibly add it to a HashMap yet
}
public static void setupMsgMap() { //this will need to be called from outside AFTER initialization
for (Message msg : values()) { //loop through all the enum constants
Msgmap.put(msg, msg.message); //add them all to the HashMap
}
}
}