This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Java in General and the fly likes Generics and enums Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Generics and enums" Watch "Generics and enums" New topic
Author

Generics and enums

Frans Janssen
Ranch Hand

Joined: Dec 29, 2004
Posts: 357
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.


SCJP 1.4, SCJD
Jesper de Jong
Java Cowboy
Bartender

Joined: Aug 16, 2005
Posts: 12953
    
    3

Try this.

You call this by passing the constructor a Class object that represents the type of an enum. For example:


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Frans Janssen
Ranch Hand

Joined: Dec 29, 2004
Posts: 357
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
Bartender

Joined: Aug 16, 2005
Posts: 12953
    
    3

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

Joined: Dec 29, 2004
Posts: 357
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.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Generics and enums
 
Similar Threads
Generics Enum type values?
Generic method in enum. Possible?
Enum to String array
Iterating through unknown enum type variable
generic enum and the values() method