Win a copy of Event Streams in Action this week in the Java in General forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

Writing a generic method with an enum

 
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I currently have a utility method that will take in an enum, and convert that enum into a List of SelectItem objects to display on in a SelectOneMenu in JSF. Here is that method:



This uses the enum.name() as both the code and the label for the SelectOneMenu. What I would like to do, is to be able to set up an enum with a description as shown below, and use that description as the label:



In this example, I'd create an interface called Selectable that would force the user to implement the getDescription() method. I'd like to modify the method that creates the SelectItems to only take in an enum which implements the Selectable interface. I'm not sure how to do this. When I start thinking about generics, I just get lost. Any help would be appreciated.
 
Sheriff
Posts: 21775
103
Eclipse IDE Spring VI Editor Chrome Java Ubuntu Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can enforce generic types to implement an interface as well, using &: <E extends Enum<E> & Selectable>.

You still need to edit your for loop, because Enum<E> isn't Selectable. However, E is, and enumClass.getEnumConstants() returns an E[]. So:
 
J Miller
Ranch Hand
Posts: 80
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is exactly what I was looking for. Thanks!
 
Rob Spoor
Sheriff
Posts: 21775
103
Eclipse IDE Spring VI Editor Chrome Java Ubuntu Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
He repaced his skull with glass. So you can see his brain. Kinda like this tiny ad:
Java Code Review and Psychology
https://coderanch.com/t/714798/java/Java-Code-Review-Psychology
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!