Anonymous classes of enum constants and var

Pavel Rappo pavel.rappo at oracle.com
Wed Feb 21 12:14:07 UTC 2024


>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 
> 
> 
> 
> 



More information about the discuss mailing list