Class EnumMapUtil
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
ObjectInputStream
where 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
-
Method Summary
-
Constructor Details
-
EnumMapUtil
public EnumMapUtil()
-
-
Method Details
-
getKeyType
public static <K extends Enum<K>,V> Class<K> getKeyType(EnumMap<K, V> enumMap) throws IOException, ClassNotFoundException- Throws:
IOException
ClassNotFoundException
-