• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Rob Spoor
  • Bear Bibeault
Saloon Keepers:
  • Jesse Silverman
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • Al Hobbs
  • salvin francis

Iterating through unknown enum type variable

 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why don't you just pass the Enum array returned from the values() method?
 
steve claflin
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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:

 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for posting back your solution!
 
You showed up just in time for the waffles! And this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic