Is there a way to restrict a method to only take certain members of an enumeration. Let's say you had an enumeration of military and enlisted ranks. If I wanted a function that only could take officer ranks and another that could only take enlisted ranks, I don't think there's a way to do that in Java, is there?
Asked
Active
Viewed 878 times
1
-
2could you post some code on what you're trying to do? Got lost readying. Sorry. – javarebel Oct 17 '12 at 22:01
-
Something like SecurityEnumSet = any of { A B C } and MonkeyEnumSet = { B D E } where the type of { A B C D E } are all SpecialEnumType ? – BRPocock Oct 17 '12 at 22:09
-
If you want to guarantee it with the type system, then they need to be distinct types, yes. – Louis Wasserman Oct 17 '12 at 23:24
1 Answers
2
Your only option is to use distinct enums, as a method taking an enum as a parameter will take any of its values at compile time.
IDEs help with the typing.

Frank Pavageau
- 11,477
- 1
- 43
- 53
-
I was afraid of that. The IDE is not helping. Eclipse 3.6 refuses to find the enumerations I want to use even when its statically imported into the class where I'm calling it or into the class containing the relavent methods. I was hoping because they were contained in EnumSets that I could use that, but i guess not. – ggb667 Oct 17 '12 at 22:28
-
I did indeed put the various enums in an interface, who has a inner class that holds the enums data. They each have a constructor that calls that class and a getter method that gets it which is part of the interface they all implement. Its the best I could do, but its still a lot of typing. Word to the wise, avoid static anything in enums. – ggb667 Oct 18 '12 at 22:09