Search code examples
javaenumsenumset

EnumSet methods won't recognize any enum types as enums


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.


Solution

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