Add EnumMap.keyType() and EnumSet.elementType()

Stephen Colebourne scolebourne at joda.org
Thu Dec 7 12:09:40 UTC 2017


I'm surprised I've never run into this. This seems like a simple and
useful change.
Stephen

On 7 December 2017 at 11:40, Andrej Golovnin <andrej.golovnin at gmail.com> wrote:
> Hi all,
>
> it would be nice if we would have access to the class of the enum type
> used to create an EnumMap or an EnumSet.
>
> This is usefull when you write a custom serialization library and
> would like to serialize/deserialize an empty EnumMap or an empty
> EnumSet. For the empty EnumSet there is a workaround to get the enum
> class:
>
> EnumSet<MyEnum> empty = EnumSet.noneOf(MyEnum.class);
> EnumSet<MyEnum> tmp = EnumSet.complementOf(empty);
> Class<?> elementType = tmp.iterator().next().getClass();
>
> But this only works when the enum class has at least one enum. For
> EnumMap there is no such workaround at all and we have to use the
> Reflection API. And you know the warnings since Java 9 :-) :
>
> WARNING: An illegal reflective access operation has occurred
> WARNING: Illegal reflective access by c.r.r.k.EnumMapSerializer to
> field java.util.EnumMap.keyType
> WARNING: Please consider reporting this to the maintainers of
> c.r.r.k.EnumMapSerializer
> WARNING: Use --illegal-access=warn to enable warnings of further
> illegal reflective access operations
> WARNING: All illegal access operations will be denied in a future release
>
> So to avoid this warning and to avoid that our application stops to
> work with a future release of Java I would like to propose to add the
> following two methods:
>
> EnumMap:
>     /**
>      * Returns the {@code Class} object of the key type for this enum map.
>      *
>      * @return the {@code Class} object of the key type for this enum map.
>      *
>      * @since 10
>      */
>     public Class<K> keyType()
>
>
> EnumSet:
>     /**
>      * Returns the {@code Class} object of all the elements of this set.
>      *
>      * @return the {@code Class} object of all the elements of this set.
>      *
>      * @since 10
>      */
>     public Class<E> elementType()
>
> The suggested change is attached as diff.
>
> Best reagrds,
> Andrej Golovnin


More information about the core-libs-dev mailing list