Anonymous classes of enum constants and var
Tagir Valeev
amaembo at gmail.com
Wed Feb 21 13:05:34 UTC 2024
There's a withdrawn JEP 301 which tried to address this issue, among other
things (see "Sharper typing of enum constants" section):
https://openjdk.org/jeps/301
Unfortunately, this was never implemented due to issues in the part that
suggested making enums generic. I'm not aware of issues in "sharper typing"
alone (without the "generic" feature). Probably it could be done
separately, but likely nobody wants to invest resources in this.
With best regards,
Tagir Valeev.
On Wed, Feb 21, 2024 at 1:14 PM Pavel Rappo <pavel.rappo at oracle.com> wrote:
> From https://mail.openjdk.org/mailman/listinfo/discuss, this mailing list
> is not suitable for questions like this. I'm not sure which mailing list is
> *the most* suitable, but the following one is surely more suitable:
> https://mail.openjdk.org/pipermail/amber-dev/ (CC'ed).
>
> I believe, the reasons why the first snippet of yours works, but the
> second doesn't, is covered here:
>
> *
> https://docs.oracle.com/javase/specs/jls/se21/html/jls-8.html#jls-8.9.1
> (like you said)
> *
> https://docs.oracle.com/javase/specs/jls/se21/html/jls-14.html#jls-14.4.1
>
> I would be surprised if that could change to allow your second snippet.
> That said, if that functionality is truly required, you can provide it
> yourself.
>
> The design of enums allows you to declare a method on an enum class and
> then override it in a particular constant. Alternatively, you can switch on
> an enum constant to provide constant-specific behaviour "externally".
>
> -Pavel
>
> > On 21 Feb 2024, at 10:08, Red IO <redio.development at gmail.com> wrote:
> >
> > I recently tinkered a bit with java enums. While I was researching edge
> features enums support I came across a stackoverflow post referencing the
> JLS 8.9 saying that the optional body of an enum constant is an anonymous
> class declaration.
> > As for some time now methods declared in an anonymous class assigned to
> a var variable are accessible I tried to do the same for the enum constant.
> >
> > var anonymous = new Object() {
> > public void test() {}
> > }
> > anonymous.test(); //works
> >
> >
> > enum Test {
> > A {
> > public void test() {}
> > }
> > }
> > var enumConstant = Test.A;
> > enumConstant.test(); // doesn't work
> >
> > I have a clue to why this doesn't work. It's likely that the type of the
> constant A is the type of the enum and not of the anonymous class.
> >
> > There are some usecases where exclusive methods on enum constants might
> be useful. So it would be nice if this would work.
> >
> > Great regards
> > RedIODev
> >
> >
> >
> >
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20240221/1a5b5c15/attachment.htm>
More information about the amber-dev
mailing list