Enhanced Enums Redux (with working code)

Clement Cherlin ccherlin at gmail.com
Sun Feb 22 18:21:23 UTC 2026


Greetings,

I have been working on the problem of generic enums off and on for quite
some time (see https://github.com/Mooninaut/cursed-generic-enum-java for a
previous dead-end attempt).

I think I have an actual solution this time, and it doesn't require any
changes to Java's type system. It only requires a slight tweak to the
"extends" clause of generic enums: Replace "extends Enum<SomeEnum<T>>" with
"extends Enum SomeEnum<?>>".

I have a fully-worked example of this at
https://github.com/Mooninaut/java-generic-enums implementing the example
given in
https://mail.openjdk.org/pipermail/amber-spec-experts/2017-May/000041.html,
which was the stopping point for the original generic enums effort.

I included lightly modified copies of Enum, EnumSet and EnumSet's
subclasses, and a Main class which demonstrates that the original problems
with collections of enums are almost entirely resolved.

I also provide several generic enums with non-trivial type bounds to
demonstrate that generic enums are no more limited than any other generic
class.

I cannot say definitively that every conceivable generic type will work,
but I haven't yet found any generic enum that wouldn't compile and run
successfully.

There is one slightly awkward issue. It's not possible to simply pass an
enum class literal to EnumSet's static factory methods without a raw cast.

EnumSet.allOf((Class<Option<?>>) (Class) Option.class);

But this can be worked around by taking advantage of the fact that
getDeclaringClass casts to Class<E>

EnumSet.allOf(Option.D.getDeclaringClass());

Cheers,
Clement Cherlin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20260222/4a088a76/attachment.htm>


More information about the amber-dev mailing list