• Post Reply Bookmark Topic Watch Topic
  • New Topic

Writing a generic method with an enum  RSS feed

 
J Miller
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.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java 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: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!