我已经定义了这个枚举:
public enum UsageType {
START("start"),
PAUSE("pause"),
RESUME("resume"),
STOP("stop"),
DESTROY("destroy");
private final String mType;
private UsageType(String type) {
mType = type;
}
/**
* Get the string representation of the UsageType
* @return string representation of the UsageType
*/
public String getAsText() {
return mType;
}
}
在另一个类中,我有一个接受字符串的构造函数,我想用该字符串创建一个枚举:
public class AppUsage {
private String mActivityName;
private String mFormattedTime;
private UsageType mUsageType;
public AppUsage(String activityName, String formattedTime, String usageType) {
mActivityName = activityName;
mFormattedTime = formattedTime;
mUsageType = mUsageType.valueOf(usageType); //HERE STRING TO ENUM!
}
//Setters and Getters....
这是我得到的错误:
java.lang.IllegalArgumentException: start is not a constant in com.embedonix.mobilehealth.serverwork.usage.UsageType
at java.lang.Enum.valueOf(Enum.java:198)
at com.embedonix.mobilehealth.serverwork.usage.UsageType.valueOf(UsageType.java:6)
最佳答案
试试 UsageType.valueOf(usageType.toUpperCase())
。当您使用该方法时,字符串应与常量名称 (START
) 匹配,并且大小写很重要。
请注意,我使用的是枚举名称 UsageType
,因为 valueOf
是一个静态方法。所以,你应该在那里需要一个实例。
此外,请注意,如果不存在具有该名称的常量,valueOf
方法会抛出 IllegalArgumentException
,运行时异常。
关于java - 在 Java 中将字符串转换为枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23681465/