如果映射不为空,则可以检索一个键并检查其类.否则唯一的方法是通过反射访问EnumMap的keyType私有字段(该字段不通过公共API公开).
在第一种情况下,你可以这样做:
Iterator> it = map.keySet().iterator();
while (it.hasNext()) {
Object key = it.next();
if (key != null) return key.getDeclaringClass();
}
在第二种情况下(显然也适用于非空枚举),您可以使用:
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的内部实现发生变化,这可能会破坏,最好找到满足您需求的方法.