1

I would like to know if it's possible to set an enum's value by specifying one of its attributes. E.g. suppose that I have the following enum:

public enum Example
    {
    EXONE("Exone", 1), EXTWO("Extwo", 3);
    private final String type;
    private final int number;


    Example(String type,int number)
        {
        this.type = type;
        this.number = number
        }

    public String getType()
        {
        return this.type;
        }

    public int getNumber()
        {
        return number;
        }
    }

Now assume that I would like to get the value EXTWO and store it inside a variable. Is it possible to do this by providing a String equal to the type-attribute? Something like:

String attribute = "Extwo";
Example ex_1 = Example.attribute

The above lines obviously will not work but I hope they clarify what I would like to do. Thanks a lot

2
  • Not exactly a duplicate, but very similar: stackoverflow.com/questions/1080904/… . See if it helps. Commented Oct 31, 2019 at 14:14
  • Thanks a lot to everybody for the links! I was able to solve it! Commented Oct 31, 2019 at 17:06

1 Answer 1

1

You may want to use valueOf() method associated with every enum,

Example ex_1 = Example.valueOf(attribute.toUpperCase());
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! valueOf() works nicely!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.