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?

3

4 Answers 4

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.

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

Comments

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

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.