-3

I already created Enum. But i cannot create new Enum. I wanna create and compare 2 Enums actually. The X value is coming from backend. It's a dynamic value. I wanna make this;

EmployeeType type = new EmployeeType("X")

if (type == EmployeeType.X_PERSONALS) {
    Log.i("SAMPLE_TAG", "Yesss!")
}
public enum EmployeeType {
    X_PERSONALS("X"),
    Y_PERSONALS("Y"),
    Z_PERSONALS("Z");

    private final String text;

    EmployeeType(final String text) {
        this.text = text;
    }

    public String getText() {
        return text;
    }
}
Emefar
  • 156
  • 1
  • 8
  • 3
    "But i cannot create new Enum" this is literally the point of enums: you can't instantiate them. You can refer to the existing elements, like `EmployeeType type = EmployeeType.X_PERSONALS;`. – Andy Turner Jan 12 '22 at 10:33
  • "X" value is coming from backend. It's a dynamic value. – Emefar Jan 12 '22 at 10:35
  • 3
    Then what you are looking for is probably: [How to get the enum type by its attribute?](https://stackoverflow.com/questions/7888560/how-to-get-the-enum-type-by-its-attribute/30212636) – OH GOD SPIDERS Jan 12 '22 at 10:36
  • 2
    But you should include that information in your question, not in a comment. That information is vital to understand what you actually have problems with – QBrute Jan 12 '22 at 10:37

2 Answers2

4

But i cannot create new Enum

This is literally the point of enums: you can't instantiate them.

You can refer to the existing elements e.g.

EmployeeType type = EmployeeType.X_PERSONALS;
Andy Turner
  • 137,514
  • 11
  • 162
  • 243
3

So what you are actually trying to achieve is to find the enum constant that has the same text. You can to that like this:

public enum EmployeeType {
    X_PERSONALS("X"),
    ///...and so on

    public static EmployeeType getByText(String x) {
        for(EmployeeType t:values()) {
            if(t.text.equals(x)){
                return t;
            }
        }
        return null;
    }
}

and then use the code like this:

EmployeeType type = EmployeeType.getByText("X");
if (type == EmployeeType.X_PERSONALS) {
    //and so on
f1sh
  • 11,489
  • 3
  • 25
  • 51