【问题标题】:How to retrieve values from Enums stored in a map?如何从存储在地图中的枚举中检索值?
【发布时间】: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 的回答!

标签: java enums constants maps


【解决方案1】:

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

声明一个接口:

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

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

public enum Test1 implements Foo { ...

现在您可以将地图更改为

Map<String, Collection<Foo>> testMap 

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 2015-11-12
    • 1970-01-01
    相关资源
    最近更新 更多