5

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?

11
  • 5
    Use values() unless you need to use reflection. Commented Feb 12, 2021 at 5:08
  • @Slaw Any possible scenarios where reflection is to be used? other than the one I have mentioned Commented Feb 12, 2021 at 5:14
  • 6
    The simple answer is that you only need getEnumConstants() when the type is only known at runtime. If you have static access to the class at compile-time, there's no reason not to use values(). Commented Feb 12, 2021 at 5:17
  • 2
    @ernest_k I suggest you make an Amswer of that Comment, so this page can be resolved. Commented Feb 12, 2021 at 7:00
  • 1
    @Gautham M The question you mentioned prints test results from JDK1.8, but if you run it on JDK16 the output has hugely different timing results in favour of values(). Commented Feb 12, 2021 at 13:17

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Updated the question with code for the generic method example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.