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 Iterating through unknown enum type variable Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Iterating through unknown enum type variable" Watch "Iterating through unknown enum type variable" New topic
Author

Iterating through unknown enum type variable

steve claflin
Ranch Hand

Joined: Dec 04, 2008
Posts: 53
I'd like to pass any enum to a function and use the values array. But, since that method is not inherited, I can't find a way to do that.

Something like:

Right now I'm accomplishing this by looping through the enum in the code that calls this, building an ArrayList<String>, and passing that to an appropriate constructor. But, I'd rather not require users to do the prep work if it can be avoided.

I think that I could use a Class object with reflection to find the values method, but would then need to figure out what the right class declaration type parameter is, and what the right constructor parameter type is, so that I could limit it to enums.
Kevin Workman
Ranch Hand

Joined: Sep 28, 2010
Posts: 151
Why don't you just pass the Enum array returned from the values() method?
steve claflin
Ranch Hand

Joined: Dec 04, 2008
Posts: 53
Kevin Workman wrote:Why don't you just pass the Enum array returned from the values() method?


Because that doesn't seem very user-friendly if I'm providing a tool as part of an API. For the task "I'd like a set of radio buttons (or a combobox) representing all the options in an Enum", it seems most natural to pass the enum class itself.

I finally did get a version that worked, using java.util.EnumSet:

Jesper de Jong
Java Cowboy
Bartender

Joined: Aug 16, 2005
Posts: 12907
    
    3

Thanks for posting back your solution!


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
 
I agree. Here's the link: http://jrebel.com/download
 
subject: Iterating through unknown enum type variable
 
Similar Threads
Generics Enum type values?
SCJP 5: Q on enums
Generics and enums
Simple J2SE 5.0 Tiger Notes
generic enum and the values() method