Win a copy of 97 Things Every Java Programmer Should Know 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
  • Paul Clapham
  • Jeanne Boyarsky
  • Junilu Lacar
  • Henry Wong
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Tim Cooke
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Frits Walraven
  • Tim Holloway
  • Carey Brown
Bartenders:
  • Piet Souris
  • salvin francis
  • fred rosenberger

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: 21950
106
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: 21950
106
Eclipse IDE Spring VI Editor Chrome Java Ubuntu Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
Dinner will be steamed monkey heads with a side of tiny ads.
Devious Experiments for a Truly Passive Greenhouse!
https://www.kickstarter.com/projects/paulwheaton/greenhouse-1
    Bookmark Topic Watch Topic
  • New Topic