• Post Reply Bookmark Topic Watch Topic
  • New Topic

refactoring enums  RSS feed

 
Stuart Rogers
Ranch Hand
Posts: 141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greetings all,

I have a class that contains a passel of enums. Currently every enum contains the method isAllColumnNamesCorrectInFirstRow,
identical except for referencing its own enum explicity within itself

within enum EenumA,


within enum EenumB,


and so on.

How can I avoid replicating this method for each enum? Could I have a static method in the class containing all the enums but outside of any enum like this?

within class AllMyEnums


which in my application I'd call with



Any ideas?


TIA,

Still-learning Stuart
 
Rob Spoor
Sheriff
Posts: 21131
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Apparently your two enums have some methods in common. Usually that would warrant a common super class, but since enums cannot have explicit super classes (they always extend java.lang.Enum) that's not an option. So create an interface for the common methods, and have both enums implement that interface. Then create a static method (preferably in a utility class, not in the enum classes) that takes an array of references of that interface:
Calling is then simply a matter of using EenumA.values() or EenumB.values().

If you don't want to use EenumA.values() there is also the option to limit the method further to enum classes. For that your method needs its own generic type, to bind both to Enum and MyEnumInterface:

Now you call it with EenumA.class and EenumB.class instead of EenumA.values() and EenumB.values().
 
Stuart Rogers
Ranch Hand
Posts: 141
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Genius!! I'll give it a try!

Thanks for your reply!

CASE CLOSED


Still-learning Stuart
 
Rob Spoor
Sheriff
Posts: 21131
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!