【发布时间】:2021-01-26 10:12:45
【问题描述】:
如何从存储在地图中的枚举中获取值?
我在一个类中有多个枚举类型。这些枚举类型存储为映射中的值。我的要求是从特定枚举类型(名称作为参数传递)中获取值。
在以下示例中,Test1 和 Test2 存储在映射中。我想为传递的 x 值和枚举类型(Test1 和 Test2..)获取对应的 Y 值。
public class TestClass {
public enum Test1 {
Const1("x1", "y1"),
Const2("x2", "y2");
private String x;
private String y;
Test1(String x, String y) {
this.x = x;
this.y = y;
}
}
public enum Test2 {
Const1("x1", "y1"),
Const2("x2", "y2");
private String x;
private String y;
Test2(String x, String y) {
this.x = x;
this.y = y;
}
}
public static final Map<String, Collection<? extends Enum<?>>> testMap = Collections.unmodifiableMap(
new HashMap<String, Collection<? extends Enum<?>>>() {
{
put("Test1", Arrays.asList(Test1.values()));
put("Test2", Arrays.asList(Test2.values()));
}
}
);
//get function to be called from outside
public static String getValueY(String x, String enumType) {
return testMap.get(enumType).stream()....
}
public static void main(String[] args) {
getValueY("x1", "Test1"); //This should give value as y1
}
}
【问题讨论】:
-
我不明白你的问题。如果要获取属于枚举的字段,则需要添加 getter 方法,例如
String getX(),与 Y 相同。然后,在迭代枚举列表时,只需调用 getter 方法,具体取决于结果,你做任何你需要做的事情。 -
感谢您的评论。是的,我忘了在这里添加。但是我如何得到我需要从哪个枚举中获取这个值 X 呢?我将在运行时获得枚举的名称,例如 Test1。
-
您有一个将“Test1”映射到枚举常量列表的映射。然后您检查枚举常量 getX() 是否返回您正在寻找的那个?仍然不确定您要的是什么,或者您正在苦苦挣扎。
-
实际上我无法从 Test1 的映射返回的值中获取此 getX() 函数。我不想使用反射。有什么简单的方法吗?
-
感谢@GhostCat 的回答!