Anonymous classes of enum constants and var
Red IO
redio.development at gmail.com
Wed Feb 21 10:08:18 UTC 2024
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/discuss/attachments/20240221/4b79eb8e/attachment.htm>
More information about the discuss
mailing list