Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Java by (3.9k points)

I have an enum,

public enum Blah

{

  Q,W,E,R

}

And I want to find the enum value of a string, for example, "Q"  which would be Blah.Q . How can I do this?

Is the Enum.valueOf() the method I need? If so, how would I use this?

1 Answer

0 votes
by (46k points)

Yes, Enum.valueOf() will work fine.

Blah.valueOf("Q") will give you Blah.Q.

Here’s the method you can use to find the enum value of a string:

 /**

* A general method for all enums since they can't have another base class

* @param <T> Enum type

* @param c enum type. All enums must be all caps.

* @param string case insensitive

* @return corresponding enum, or null

*/

public static <T extends Enum<T>> T getEnumFromString(Class<T> c, String string) {

   if( c != null && string != null ) {

       try {

           return Enum.valueOf(c, string.trim().toUpperCase());

       } catch(IllegalArgumentException ex) {

       }

   }

   return null;

}

0) : "length is too short"));


 

If you have any doubts, mention them in the comment section below.

Related questions

0 votes
1 answer
0 votes
2 answers
asked Nov 23, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Oct 17, 2019 in Java by Anvi (10.2k points)
0 votes
2 answers
asked Nov 25, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...