Enhanced Enums Redux (with working code)
Clement Cherlin
ccherlin at gmail.com
Mon Feb 23 00:30:56 UTC 2026
On Sun, Feb 22, 2026, 2:26 PM Chen Liang <chen.l.liang at oracle.com> wrote:
> Hi Clement, I think the issue you've discovered is already considered in
> the original proposal, in the "Too raw?" section:
> https://cr.openjdk.org/~mcimadamore/amber/enhanced-enums.html#too-raw
> TLDR; a reifiable type doesn't work with class literals.
>
> Regards
>
That conclusion should be revisited. Reifiable types work perfectly fine
with class literals, as long as you're willing to cast class literals to
unerased types, and accept the fact that unerased types only truly exist at
compile time. That's nothing new; all Java generics only truly exist at
compile time (ignoring reflection).
The only significant flaw would be if users were required to perform the
awkward erased-to-raw-to-unerased cast every time they wanted to use
EnumSet/EnumMap. But they don't. The method
EnumClass.CONSTANT.getDeclaringClass(), a method which already exists, has
exactly the desired properties. It produces the correct statically-typed
cast of EnumClass.class, suitable for use in any API that requires a
properly-typed Class literal, such as EnumSet, without any modification to
either existing JDK code or the Java type system.
As proof, I submit
https://github.com/Mooninaut/java-generic-enums/blob/main/src/main/java/org/duckdns/mooninaut/genericEnum/Argument.java
The claim "While in principle we could tweak the supertype of a generic
enum to be Enum<Foo<?>> instead of Enum<Foo>, doing so would quickly run
out of gas when considering examples such as the stream method chain shown
above" is shown to be inaccurate.
The code
Arrays.stream(Argument.values())
.filter(a -> Number.class.isAssignableFrom(a.getClazz()))
.collect(toCollection(() ->
MyEnumSet.noneOf(Argument.STRING_ARGUMENT.getDeclaringClass())));
compiles and executes with no issues.
It's inelegant, but it works. If elegance were required to adopt a feature
into the JDK, we certainly wouldn't have generics in their current form.
Cheers,
Clement Cherlin
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20260222/aa48b635/attachment-0001.htm>
More information about the amber-dev
mailing list