EnumSet
has an private field for the value class. Why not provide public access?
Also, EnumMap
has private fields for key and value classes. Same question.
For non-empty sets/maps, it is possible iterate the first element and extract class from a non-null value. However, for empty sets/maps, this is not possible.
The reason there is no getter-method for the member class of an
EnumSet
nor for the key class ofEnumMap
is that in order to use these classes effectively, the static type is generally known and used by the programmer, and the type'sClass
can easily be derived from the type name using a class literal.For example, consider the following enum:
You'd use it like this:
To add, remove, or check membership in this set, we generally have a
Direction
instance. If we want to create a new set or derive one from an existing set, we'd declare a variable of typeSet<Direction>
. If we want theClass
object corresponding to the enum type, we just useDirection.class
. Thus there is generally no need to get theClass
object out of theEnumSet
itself.Similar reasoning applies to
EnumMap
.I suppose there might be some case out there where one has an instance of an
EnumSet<?>
and you want to create a set of all or none of the enum values, which requires theClass
object for a type not known at compile time. Such a case would seem to be quite contrived. For such cases, though, one could use this equally contrived technique (i.e., hack) to get the enum class for some unknown EnumSets
:A similar technique could probably be used to get the key class of an
EnumMap
.