Muhammad Saad
Muhammad Saad

Reputation: 61

Java Lookup Enum By String Value

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?

Upvotes: 0

Views: 458

Answers (4)

Yuvaraj Ram
Yuvaraj Ram

Reputation: 67

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

Upvotes: 0

Deb
Deb

Reputation: 2972

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.

Upvotes: 2

dsncode
dsncode

Reputation: 2441

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;
    }

Upvotes: 0

yassadi
yassadi

Reputation: 524

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().

Upvotes: 0

Related Questions