Java枚举|在构造函数中创建了映射|但无法访问/发送其值



使用参数在枚举中创建映射

  • 键:AUTQ-值:AUTP
  • 关键字:FAUQ-值:FAUP

我创建了映射,但现在在枚举中陷入了静态和非静态调用

AUTHOR("AUTQ","AUTP"), <--- Author is of no use but the values AUTQ is Key and AUTP is value
FINA("FAUQ","FAUP"),
private final Map<String, String> val;
MessageFunction(String key, String value){
this.val = new HashMap<>();
this.val.put(key.toUpperCase(), value); <--- Created a Map
}
public static String getResultValue( String fromValue) {

return this.val.get(fromValue.toUpperCase()); <--- How to access it?
}

当我添加static时,它不允许调用this.val(不能从静态上下文引用(

当我添加非静态时,不知道如何在代码中调用它。

你能建议一下如何处理这个用例吗?

您可以在静态块中创建映射内容。

public enum MessageFunction {
AUTHOR("AUTQ", "AUTP"),
FINA("FAUQ", "FAUP");
private static final Map<String, String> val;
static {
val = Arrays.stream(MessageFunction.values())
.collect(Collectors.toMap(my -> my.key.toUpperCase(), my -> my.value));
}
MessageFunction(String key, String value) {
this.key = key;
this.value = value;
}
private final String key;
private final String value;
public static String getResultValue(String fromValue) {
return val.get(fromValue.toUpperCase());
}
}

以下两个调用都打印AUTP

System.out.println(MessageFunction.getResultValue("AUTQ"));
System.out.println(MessageFunction.getResultValue("autq"));

最新更新