File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Generics and enums Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
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
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14266
    
  21

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 8 API documentation
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
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14266
    
  21

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://aspose.com/file-tools
 
subject: Generics and enums