0

I have the following enum:

public enum UserRole {
    ADMIN,
    MANAGER,
    OPERATOR
}

I need to get the UserRole value from its corresponding numeric value as shown below:

String role = "0";
UserRole userRole = UserRole.valueOf(role); // I am expecting to get UserRole.ADMIN

It throws "java.lang.IllegalArgumentException: No enum constant com.mycompany.domain.model.UserRole.... java.base/java.lang.Enum.valueOf(Enum.java:240)". So, do I need to make some implementation in the UserRole class?

Jack
  • 1
  • 21
  • 118
  • 236
  • Enum values automatically have ordinal values, but don't rely on them: the ordinal changes if the values are reordered, new values are inserted etc. If you want to be able to convert a number to an enum value, make the number an explicit property of the enum value, and search the values for a match. – Andy Turner Oct 14 '21 at 13:26
  • Very useful info. Then should I assign int numbers to enum values? How? – Jack Oct 14 '21 at 13:39
  • 1
    Look at the [Planet example](https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html). – Andy Turner Oct 15 '21 at 12:36

0 Answers0