To get the array of enum
constants of some Enum
type TestEnum
, we have two options - TestEnum.values()
or TestEnum.class.getEnumConstants()
. When I looked at the code, I could see that the getEnumConstants()
is invoking the values()
method through reflection and then caching it for future usage. Before returning, the array is cloned as well.
From the below question and its answers (which focuses only on performance), it seems that there aren't much difference in performance.
Comparison of enums values() method and class.getEnumConstants()
I would like to know whether one of these methods is preferred over the other. One scenario which I could think of is when creating a method which works on generics where we pass a generic enum
class as the argument. In this case, we could only use the getEnumConstants
approach.
Are there any other similar scenarios? If I am sure about the type of the enum
which I am going to use, then isn't it better to use values()
approach?
Aucun commentaire:
Enregistrer un commentaire