假设我的String
枚举中有多个字段(int
或Java
),我希望动态地按名称获取字段值。
public enum Code {
FIRST("valueForFirst"),
SECOND("valueForSecond");
// etc
}
然后我得到了我想要的字段名称:
String fieldName = getEnumFieldName(); // can be: "FIRST" or "SECOND"
// now get "fieldName"'s value from Code
我该怎么做?
答案 0 :(得分:4)
您需要使用Enum.valueOf();
,例如:
Code c = Code.valueOf(Code.class, fieldName);
答案 1 :(得分:2)
如果您从字符串形式的其他位置获取字段的名称,则可以使用valueOf()
方法获取Enum实例..但是,首先您需要以全部大写形式转换字符串.. < / p>
String fieldName = getEnumFieldName();
Code first = Code.valueOf(fieldName);
String value = first.getValue();
完成本教程 - http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html,了解有关如何使用Enums
的更多信息..
答案 2 :(得分:2)
您可以像这样定义枚举:
public enum Code {
private String value;
public Code(String value) {
this.value = value;
}
public String getValue() {
return value;
}
FIRST("valueForFirst"),
SECOND("valueForSecond");
}
然后像这样使用它:
Code code = Code.FIRST;
String val = code.getValue();
或者像这样:
String key = "FIRST";
Code code = Code.valueOf(key);
String val = code.getValue();
如果您想从代码中获取“FIRST”,请执行
String name = code.name();
答案 3 :(得分:1)
您可以在枚举上使用valueOf()
方法。
String fieldName = "FIRST"; // or "SECOND"
Code c = Code.valueOf(fieldName);
答案 4 :(得分:0)
这是我使用的模式:
enum X {
A("a"), B("b"), ...;
private final static Map<String,X> MAP = new HashMap<String,X>();
static {
for( X elem: X.values() ) {
if( null != MAP.put( elem.getValue(), elem ) ) {
throw new IllegalArgumentException( "Duplicate value " + elem.getValue() );
}
}
}
private final String value;
private X(String value) { this.value = value; }
public String getValue() { return value; }
// You may want to throw an error here if the map doesn't contain the key
public static X byValue( String value ) { return MAP.get( value ); }
}
在enum
声明中的static
块中访问enum
类型的实例看起来有点奇怪,但此代码有效。
在你的情况下,可能会这样:
String fieldName = Code.valueOf(Code.class).getValue();
答案 5 :(得分:0)
public enum Code {
FIRST("valueForFirst"),
SECOND("valueForSecond");
}
public class Test{
Code c;
public static void main(String[] args){
Test t = new Test();
String val = t.c.FIRST.getValue();
}
}