Java 枚举 |在构造函数中创建地图 |但不能 access/send 它的价值
Java Enum | Created map in constructor | But cannot access/send its value
使用参数在枚举中创建地图
- 键: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?
}
当我添加静态时,它不允许调用 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"));
使用参数在枚举中创建地图
- 键: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?
}
当我添加静态时,它不允许调用 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"));