Class EnumMapUtil

java.lang.Object
com.google.gwt.user.server.rpc.EnumMapUtil

public class EnumMapUtil extends 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
      };
      EnumMapinvalid input: '<'MyBoolean, Integer> enumMap = new EnumMapinvalid input: '<'>(MyBoolean.class);
      Classinvalid input: '<'?> 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.