Which usage is preferred Enum.values() or Enum.class.getEnumConstants()?

Viewed 153

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.

<E extends Enum<E>> void doSomething(Class<E> clazz){
    for(E type : clazz.getEnumConstants()){
        // do something...
    }
}

In the above 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?

1 Answers

The only answer applicable here is based on what each of these options was designed for.

Methods available on the Class class are designed for dynamic, runtime inspection of classes, so Class.getEnumConstants() is to be used when the enum class to list values for is only known when the program is running. Your example of lookup in a generic method illustrates the correct use.

If you know the class statically, then you should use YourEnumClass.values(). There is no valid reason to go through a Class instance to do that.

Related