5

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?

8
  • what is Enum in your example? Commented Dec 16, 2018 at 17:27
  • I want to make it universal, so I put just Enum as type of argument to match any Enum object to this method. Commented Dec 16, 2018 at 17:28
  • And values does only work for the enum type, e.g. MyEnum.values() but clearly not for a specific value of an enum like in your method... Commented Dec 16, 2018 at 17:29
  • ok, that can't work for any enum as explained by the others in the comment Commented Dec 16, 2018 at 17:29
  • Reflection would also be a workaround, but who wants to use reflection...getDeclaredField("$VALUES"); or Enum.class.getDeclaredMethod("values"); for the enum class Commented Dec 16, 2018 at 17:31

1 Answer 1

6

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.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.