Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I can not get .values() from Enum object class?

Tags:

java

enums

I want to create universal method, for any enum object, that will check if enum has specified value name, but as Enum type object I am unnable to use method values();. Why?

Is there any way to get values from an Enum type object?

I need method like this to check if value from configuration is a valid string for myEnum.valueOf(String); because if given string will be wrong then it will throw an exception (and I do not want it).

I want my method to look like this:

public static Boolean enumContains(Enum en, String valueString){
    return toStringList(en.values()).contains(valueString.toUpperCase());
}

But there is no method Enum.values(). How to create this method correctly?

like image 671
Albert451 Avatar asked Dec 16 '18 17:12

Albert451


People also ask

Can we get an enum by value?

Get the value of an EnumTo get the value of enum we can simply typecast it to its type. In the first example, the default type is int so we have to typecast it to int. Also, we can get the string value of that enum by using the ToString() method as below.

What is the purpose of values () method in enum?

The valueOf() method of Enum class returns the enum constant(of defined enum type) along with the defined name.

Can you inherit from an enum?

Inheritance Is Not Allowed for Enums.


1 Answers

Enum#values is a method that is generated by the compiler, so you cannot use it at compile time unless you pass in a specific enum and not Enum<?>.

See: https://stackoverflow.com/a/13659231/7294647

One solution would be to pass in a Class<E extends Enum<E>> instead and use Class#getEnumConstants:

public static <E extends Enum<E>> Boolean enumContains(Class<E> clazz, String valueString){
    return toStringList(clazz.getEnumConstants()).contains(valueString.toUpperCase());
}

If you have an enum named MyEnum, then you can simply pass in MyEnum.class as the first argument.

like image 101
Jacob G. Avatar answered Oct 20 '22 21:10

Jacob G.