0

I have the following enums with their value:

How can I convert the value of an enum to the enum? For example, from "Rocky" as input how can I set the enum of a class to ROCK?

I tried using valueOf like this:

gen gen1 = gen.valueOf("Rocky")

However, it throws an IllegalArgumentException of 'No enum constant'.

I have been really trying to figure this out even though I guess it's too easy but I'm a beginner. I had to instead take direct enum constant as input instead of the value of enum as input. But I want to know for knowledge on how I can convert the value of an enum to enum constant?

  • Your enum item is `ROCK`, not `Rocky`, so `valueOf("Rocky")` is not going to work. If you want to find your enum by a field value, you'll have to loop through and check each one. – khelwood Mar 28 '21 at 11:20
  • or you have to add your own method, that returns the enum based on the value. create a static method, iterate over all the enums and if you find the right one, return it – Stultuske Mar 28 '21 at 11:20
  • If you want to use valueOf you need to give the name of the enum item, `gen.valueOf("ROCK")` or override the method. Does this answer your question? [Override valueof() and toString() in Java enum](https://stackoverflow.com/questions/9662170/override-valueof-and-tostring-in-java-enum) – Joakim Danielson Mar 28 '21 at 11:20
  • Your code does not compile. – Giorgi Tsiklauri Mar 28 '21 at 11:21

1 Answers1

0

The method valueOf is used when you have a string matching the name of the enum constant, like ROCK, POP etc. There are obviously no built in methods which can interact with your custom field, it could be anything!

So unfortunately it would have to be done manually and you would have to loop through all the enum values (which can be retrieved with Enum.values() and compare your field.

Henry Twist
  • 5,666
  • 3
  • 19
  • 44