如何找出EnumMap中使用的枚举? [英] How do I find out the enum used in an EnumMap?

查看:165
本文介绍了如何找出EnumMap中使用的枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有内部枚举和EnumMap的测试类,如下所示。如何找出EnumMap中使用的枚举?

I have a test class with an internal enum and an EnumMap like the following. How do I find out which enum is used within the EnumMap?

enum MyEnum { ENUM1, ENUM2 }
EnumMap<MyEnum, String> emap = new EnumMap<>( MyEnum.class );
public void discover() {
  Class<?> eclass = ???;
  System.out.println( eclass );
}

应打印


MyEnum.class

MyEnum.class


推荐答案

如果映射不为空,您可以检索一个键并检查其类别。否则,唯一的方法是通过反射访问EnumMap的 keyType 私有字段(该字段不会通过公共API公开)。

If the map is not empty, you can retrieve one key and check its class. Otherwise the only way is to access the keyType private field of the EnumMap via reflection (the field is not exposed through the public API).

在第一种情况下,您可以这样做:

In the first case you can do:

Iterator<?> it = map.keySet().iterator();
while (it.hasNext()) {
  Object key = it.next();
  if (key != null) return key.getDeclaringClass();
}

在第二种情况下(显然也适用于非空枚举),您可以用途:

In the second case (which obviously also works for non empty enums) you can use:

private static Class<?> enumMapType(EnumMap<?, ?> map) {
  try {
    Field keyType = EnumMap.class.getDeclaredField("keyType");
    keyType.setAccessible(true);
    return (Class<?>) keyType.get(map);
  } catch (IllegalAccessException | NoSuchFieldException e) {
    throw new AssertionError("Could not find EnumMap type", e);
  }
}

如果内部执行 EnumMap 进行更改,最好能找到解决您需求的方法。

This could break if the internal implementation of EnumMap changes and it would be better to find a way around your requirement.

这篇关于如何找出EnumMap中使用的枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆