简体   繁体   中英

Executing action depending on enum value

I'm trying to retrieving a value depending on the enum value. Basically, let's say I have the following enum:

    private enum Auth{

    KEY, PASSWORD, MAIL;    

    public String get(){
        return "";
    }
}

By doing Auth.KEY.get() it would return "mykey", while Auth.MAIL.get() would return "mymail" I googled a bit but I couldn't find an answer, I didn't try anything before because I totally hadn't an idea on how I could start.

Just add a field and constructor, as explained in the java-docs

Example code:

enum Auth {

    KEY("myKey"), PASSWORD("myPass"), MAIL("myMail");    

    private final String identifier;

    Auth(String identifier) {
        this.identifier = identifier;
    }

    public String get(){
        return identifier;
    }
}

Also note, that there is name() and toString() which may be useful: see also java-enum-why-use-tostring-instead-of-name

enum Auth{
private enum Auth{
String value;
KEY("mykey"), PASSWORD("mypassword"),    MAIL(mymail");    

Auth(String value){
thia.value=value;
}
public String get(){
    return value;
}
}

You need to have a string which holds the name of of enum and a constructor which sets it. Then get method returns the name as below.

 private enum Auth{

    KEY, PASSWORD, MAIL;    
    string name;
    public Auth(string nm) {
      name = nm;
    }
    public String get(){
        return name;
    }
 }

Although I strongly advise not to use the following mechanism for getting something simple like a hardcoded String from an enum value and rather use it for associating particular behavior like in java.util.concurrent.TimeUnit , this is how it can be achieved:

private enum Auth {

    KEY {
        public String get() {
            return "mykey";
        } 
    },

    PASSWORD {
        public String get() {
            return "mypassword";
        } 
    },

    MAIL {
        public String get() {
            return "mymail";
        } 
    };

    public abstract String get();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM