如何从存储在地图中的枚举中检索值?

How to retrieve values from Enums stored in a map?

如何从存储在地图中的枚举中获取值?

我在 class 中有多个枚举类型。这些枚举类型作为值存储在映射中。我的要求是从特定枚举类型(名称作为参数传递)获取值。

在下面的示例中,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
    }
}

一种类型安全的方法,无需反射:

声明接口:

interface Foo {
  String getX();
  String getY();

所有您的枚举实现该接口:

public enum Test1 implements Foo { ...

现在您可以将地图更改为

Map<String, Collection<Foo>> testMap 

然后允许您调用两种方法,getX()getY()