简体   繁体   English

在Java中将String转换为枚举

[英]Convert String to enum in Java

I have defined this enum : 我已经定义了这个枚举:

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;
    }
}

In another class, I have a constractor that takes string, and I want to make an enum with that string: 在另一个类中,我有一个使用字符串的承包商,并且我想用该字符串做一个枚举:

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....

Here is the error I get: 这是我得到的错误:

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)

Try UsageType.valueOf(usageType.toUpperCase()) . 尝试使用UsageType.valueOf(usageType.toUpperCase()) When you use that method, the string should match the constant name ( START ) and the case matters. 使用该方法时,字符串应与常量名称( START )相匹配,并且大小写很重要。

Note that I am using the enum name UsageType because valueOf is a static method. 请注意,由于valueOf是静态方法,因此我使用了枚举名称UsageType So, you should need an instance there. 因此,您应该在那里需要一个实例。

Also, note that the valueOf method throws IllegalArgumentException , runtime excpetion, if no constant with the name exists. 另外,请注意,如果不存在名称常量,则valueOf方法将抛出IllegalArgumentException ,运行时例外。

If uses the constant name type (the one in upper case), not the internal name you pass by parameter on the constructor. 如果使用常量名称类型(大写的一种),而不是通过构造函数中的参数传递的内部名称。

String str = "START"; // as example...could be "PAUSE", or "DESTROY", etc.
UsageType type = UsageType.valueOf(str);

Remove this constructor parameter..it's useless. 删除此构造函数参数。它没有用。 Make it simply like this: 使其简单地像这样:

public enum UsageType {
   START,
   PAUSE,
   RESUME,
   STOP,
   DESTROY;
}

and for the getAsText() just use the built in UsageType.name() . 对于getAsText()只需使用内置的UsageType.name()即可

What about this? 那这个呢?

    public AppUsage(String activityName, String formattedTime, String usageType) {
      mActivityName = activityName;
      mFormattedTime = formattedTime;
      for(UsageType type : UsageType.values())
        {
          if(type.getAsText().equals(usageType))
            mUsageType = type;
        }
      }

when i want to convert string to enum, im always using lookup map add this to your enum 当我想将字符串转换为枚举时,我总是使用查找映射将其添加到您的枚举中

private static final Map<String, UsageType> lookup = new HashMap<String, UsageType>();
    static {
        for (final UsageType s : EnumSet.allOf(UsageType.class)) {
            lookup.put(s.getAsText(), s);
        }
    }
    static public UsageType fromString(final String name) {
        return lookup.get(name);
    }

now to convert your string to enum all what you need to do is UsageType.fromString("someString"); 现在要将您的字符串转换为枚举,所有您需要做的就是UsageType.fromString("someString");

What i have observed is based on enum we can get value but not by passing value to get enum name. 我观察到的是基于枚举,我们可以获取值,但不能通过传递值来获取枚举名称。 ie Try this it is working fine for me. 即尝试这个对我来说很好。 Hope it should helpful for you. 希望对您有帮助。

public enum UsageType {    
    START("start"),
    PAUSE("pause"),
    RESUME("resume"),
    STOP("stop"),
    DESTROY("destroy");

    private final String mType;

    UsageType(String type) {
        mType = type;
    }


    public String getAsText() {
        return mType;
    }

}

public class AppUsage {

    private String mActivityName;
    private String mFormattedTime;
    public static UsageType mUsageType;

    public AppUsage(String activityName, String formattedTime, String usageType) {
        mActivityName = activityName;
        mFormattedTime = formattedTime;
        mUsageType =  UsageType.valueOf(usageType); //HERE STRING TO ENUM!
    }

    public String getmActivityName() {
        return mActivityName;
    }

    public void setmActivityName(String mActivityName) {
        this.mActivityName = mActivityName;
    }

    public String getmFormattedTime() {
        return mFormattedTime;
    }

    public void setmFormattedTime(String mFormattedTime) {
        this.mFormattedTime = mFormattedTime;
    }

    public UsageType getmUsageType() {
        return mUsageType;
    }

    public void setmUsageType(UsageType mUsageType) {
        AppUsage.mUsageType = mUsageType;
    }
 public static void main(String args[]){
//   AppUsage au=new AppUsage("a", "a","START");
     UsageType v[]=mUsageType.values();
     UsageType u=mUsageType.valueOf("START");
     System.out.println(u.getAsText());

 }
}

hope it may solve your problem 希望它可以解决您的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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