Java将选择转换为枚举
在简单代码中,我尝试Java将选择转换为枚举,java,android,enums,Java,Android,Enums,在简单代码中,我尝试enum而不是select,例如,我想转换此代码: switch (name) { case "1": return "a"; break; case "2": return "b"; case "3": return "c"; } 要枚举为: public enum ContentTypes { FREE("1"), PAYABLE("2"), INCOME("3");
enum
而不是select
,例如,我想转换此代码:
switch (name) {
case "1":
return "a";
break;
case "2":
return "b";
case "3":
return "c";
}
要枚举为:
public enum ContentTypes {
FREE("1"),
PAYABLE("2"),
INCOME("3");
private String name;
ContentTypes(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
public String getType(String type) {
return (ContentTypes) type.getName();
}
问题是contenttype
内容是值。比如说
String test = "FREE";
getType(test);
使用
您声明的每个
enum
类型都会自动获得一个内置的静态valueOf()
方法。还有一个可以使用的静态Enum.valueOf()
方法
String name = "FREE";
ContentTypes t = ContentTypes.valueOf(name);
// or
ContentTypes t = Enum.valueOf(ContentTypes.class, name);
如果我了解您的需求,您可以在其中一个API调用上构建解决方案。请注意,这些方法区分大小写,如果
name
与枚举常量不匹配,则会抛出IllegalArgumentException
。是否有原因不想使用类似a的内容?是否尝试过ContentTypes.valueOf(ContentType.class,type)
?@PakkuDon我喜欢使用Enum@Ted霍普:不,请稍等test@TedHopp谢谢,先生。解决问题。请回复接受
String name = "FREE";
ContentTypes t = ContentTypes.valueOf(name);
// or
ContentTypes t = Enum.valueOf(ContentTypes.class, name);