0

I have an enum which is just

public enum Blah {
    A, B, C, D
}

and I would like to find the enum value of a string, for example "A" which would be Blah.A. How would it be possible to do this?

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

yassadi
  • 524
  • 1
  • 9
  • 20
  • Check https://stackoverflow.com/questions/1080904/how-can-i-lookup-a-java-enum-from-its-string-value – Saeed Apr 24 '18 at 05:12
  • 1
    Possible duplicate of [How can I lookup a Java enum from its String value?](https://stackoverflow.com/questions/1080904/how-can-i-lookup-a-java-enum-from-its-string-value) – kezhenxu94 Apr 24 '18 at 05:26
  • Please try to search the solution before posting on stackoverflow. – Dhruv Raj Singh Apr 24 '18 at 06:40

4 Answers4

2

You should use Blah.valueOf("A") which will give you Blah.A.

The parameter you are passing in the valueOf method should match one of the Enum otherwise it will throw in exception.

Deb
  • 2,922
  • 1
  • 16
  • 32
0
public Blah blahValueOf(String k) {
    for (Blah c : Blah.values()) {
        if (c.getLabel().toUpperCase().equals(k.toUpperCase())) {
            return c;
        }
    }
    return null;
}

You can write this method in order to find the Blah.valueOf().

yassadi
  • 524
  • 1
  • 9
  • 20
0

you could use .valueOf method. for example

public class EnumLoader {

    public static void main(String[] args) {
            DemoEnum value = DemoEnum.valueOf("A");
            System.out.println(value);
        }
    }
    enum DemoEnum{
        A,B,C;
    }
dsncode
  • 2,407
  • 2
  • 22
  • 36
0

If you want to access the value of Enum class you should go with valueOf Method.

valueOf(argument) -> Will return the Enum values specific to argument.

System.out.println(Blah.valueOf("A"));

Remember one point if the argument were not present in Enum class, you will face java.lang.IllegalArgumentException: No enum constant

mate00
  • 2,727
  • 5
  • 26
  • 34