4

There are a number of similar questions about similar errors but they're all about specific situations where the enum type hadn't initialized before trying to make an EnumSet of that type. My problem is much, much more basic. I can't get any EnumSet methods to recognize any enum as an enum, no matter how simple what I'm trying to do is. For example:

> enum X{GREEN,RED,YELLOW}
> X.values()
{ GREEN, RED, YELLOW }
> EnumSet.allOf(X.class);
java.lang.ClassCastException: class X not an enum
   at java.base/java.util.EnumSet.noneOf(EnumSet.java:113)
   at java.base/java.util.EnumSet.allOf(EnumSet.java:132)
   at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78)
   at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 

I get the exact same error word-for-word no matter what EnumSet method I try to use. Does anyone know what I might have done wrong? I'm using DrJava with JDK 8 because that's what I learned with and I'm just doing this for fun so I don't need to be using the most up-to-date development kit, could that be the problem? Documentations says EnumSet is part of Java 8 so I assume not but I don't know.

  • I am unable to reproduce this scenario, above is working in java 8 and 11 – Vinujan.S Jun 12 '21 at 03:49
  • 1
    Though not much to do with your problem, your stack trace includes the module names (`java.base`), which seem to suggest that you're using JDK 9... – Sweeper Jun 12 '21 at 04:07
  • Your code [runs just fine on Java 12 at IdeOne.com](https://ideone.com/NHU37g). This confirms the [Answer by Sweeper](https://stackoverflow.com/a/67945496/642706), the problem likely lies with DrJava rather than with Java. – Basil Bourque Jun 12 '21 at 04:33

1 Answers1

7

This seems to be a very old bug in DrJava: #744 enums can't appear in EnumSet. It has been reported since 2009, and still is not fixed. According to the discussion, apparently X.class.isEnum() returns false, which seem to imply that when compiling the enum declaration, DrJava didn't correctly load a class that corresponds to the declaration.

I suggest that you use another IDE, such as Eclipse, IntelliJ IDEA, or if you like the Interactive REPL that DrJava has, you can use JShell, which comes with JDK 9.

Sweeper
  • 213,210
  • 22
  • 193
  • 313