[英]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.通过执行 Auth.KEY.get() 它将返回“mykey”,而 Auth.MAIL.get() 将返回“mymail” 我用谷歌搜索了一下但找不到答案,我之前没有尝试任何东西因为我完全不知道如何开始。
Just add a field and constructor, as explained in the java-docs只需添加一个字段和构造函数,如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另请注意,有name()和toString()可能有用:另请参阅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.
然后 get 方法返回名称如下。
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:尽管我强烈建议不要使用以下机制从枚举值中获取诸如硬编码
String
之类的简单内容,而是将其用于关联特定行为,例如java.util.concurrent.TimeUnit
,但这是实现方法:
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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.