This week's book giveaway is in the JavaScript forum.
We're giving away four copies of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js and have Paul Jensen on-line!
See this thread for details.
Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Generics and enums  RSS feed

 
Frans Janssen
Ranch Hand
Posts: 357
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there any way to use a generic superclass for any enum type?

I want to make a combo box that allows the user to choose from the values in an enum type. I hoped I could do something like this:



But values() is not a method defined in Enum and the constructor doesn't accept an enum type as a parameter (as apparently it isn't a subclass of Enum, even though the javadoc seems to suggest that it should be).

Does anyone know how to do this or do you have a suggestion for an elegant solution to accomplish the same thing?

Thanks in advance,

Frans.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16006
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try this.

You call this by passing the constructor a Class object that represents the type of an enum. For example:
 
Frans Janssen
Ranch Hand
Posts: 357
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jesper,

Thanks for your reply. I had to change the class declaration a bit in order to get it to compile:



However, it then crashes on a NullPointerException when constructed. Apparently the getEnumConstants() method returns null, as the Class class feels it is not an enum class (isEnum() returns false). I think that is pretty awkward, but the Javadoc of isEnum() says the following:


If I call getSuperClass() on the enum class, it tells me it derives from Object rather than enum.
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16006
87
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Strange... what are you passing to the constructor exactly? If you pass a Class object that represents the type of an enum, it should work properly. The small test program below prints:

Is it an enum? true
Value: ONE
Value: TWO
Value: THREE

 
Frans Janssen
Ranch Hand
Posts: 357
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hmmm, this looks like a "feature" of JBuilder. If I compile and run your code with the JDK tools it works perfectly, but when I compile and run it in JBuilder (2005) it returns false on isEnum() and then throws an exception because the getEnumConstants() returns null.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!