Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get enum string without toString()

If I have something like this:

public enum Collection {
    Name, Type, All
}

And I would like to use the enumkey for the string too. I can say Collection.Name.toString - thats fine. But I would like to do this without .toString Is there an easy solution for this? I saw a lot of stuff but they were too big with switch or with a lot of if. No other way? Thank you!

Edit: the solution with Collection.something.name() is nice. But is there another way to get the string with Collection.something ?

like image 400
OverStack Avatar asked Nov 30 '25 09:11

OverStack


2 Answers

Use Enum's name() method:

Collection.Name.name()
Collection.Type.name()
// etc

Edit:

I don't know if this is a valid solution, but this would work too:

Collection.Name + ""
like image 168
Bohemian Avatar answered Dec 03 '25 00:12

Bohemian


It's looks like you are searching smt like

enum Collection {
    Name("name"), Type("type"), All("all");
    String id;

    Collection(String id) {
        this.id = id;
    }

    public String getId() {
        return id;
    }
}

or

enum Collection2 {
    Name, Type, All;
    private static final Map<Collection2, String> ids;

    static {
        ids = new HashMap<Collection2, String>();
        ids.put(Name, "name");
        ids.put(Type, "type");
        ids.put(All, "all");
        //here can be sam validation on id's uniq
    }

    public String getId() {
        return ids.get(this);
    }
}
like image 38
Stan Kurilin Avatar answered Dec 02 '25 22:12

Stan Kurilin