Class EnumMapUtil


  • public class EnumMapUtil
    extends java.lang.Object
    A utility to extract the key type of any EnumMap, even if it is empty. Some frameworks have tried this by using reflection on the map's private field keyType, but that approach breaks with Java 17 where reflection on private elements of any java.* class is forbidden unless the --add-opens VM argument is used which is a fairly unsafe thing to do.

    Use like this:

          private static enum MyBoolean {
              TRUE, FALSE
          };
          EnumMap enumMap = new EnumMap<>(MyBoolean.class);
          Class c = EnumMapUtil.getKeyType(enumMap);
     

    Implementation note: If the map passed to getKeyType(java.util.EnumMap) is not empty, the first key is obtained from the key set and its type is determined and returned. If the map is empty, it is serialized into an ObjectOutputStream writing to a ByteArrayOutputStream from which it is read again with a specialized ObjectInputStreamwhere the resolveClass method is overridden. Upon reading a class descriptor for class EnumMap, instead of regularly resolving the class descriptor a package-protected class EnumMap is returned which has a serial version UID equal to that of EnumMap and the same set of fields. By having the same simple name (despite living in a different package) the ObjectInputStream considers this class to be compatible to EnumMap and de-serializes the stream contents into an instance of EnumMap which in turn offers a public getter EnumMap.getKeyType() for the key type. Through this getter the key type is then determined and returned.

    • Constructor Summary

      Constructors 
      Constructor Description
      EnumMapUtil()  
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static <K extends java.lang.Enum<K>,​V>
      java.lang.Class<K>
      getKeyType​(java.util.EnumMap<K,​V> enumMap)  
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Constructor Detail

      • EnumMapUtil

        public EnumMapUtil()
    • Method Detail

      • getKeyType

        public static <K extends java.lang.Enum<K>,​V> java.lang.Class<K> getKeyType​(java.util.EnumMap<K,​V> enumMap)
                                                                                   throws java.io.IOException,
                                                                                          java.lang.ClassNotFoundException
        Throws:
        java.io.IOException
        java.lang.ClassNotFoundException