简体   繁体   English

设置枚举的字符串值

[英]String Value to set an Enum

I would like to set an enum type by using one of its values as an input:我想通过使用枚举类型之一作为输入来设置枚举类型:

This is the code i'm using,这是我正在使用的代码,

    package models;

    import models.crudsiena.SienaSupport;
    import siena.*;

    public class Item extends SienaSupport {

        @Id
        public Long id;


           public static enum Type{
              A,
              B
            };

            public Type itemType;

            public Item(String itemType) {
               this.itemType = Type.valueOf(itemType);
            }
}

When I try to use new Item("A") it returns me a NullPointerException occured: Name is null当我尝试使用new Item("A")它返回给我一个NullPointerException occured: Name is null

Try this:尝试这个:

public Item(String itemType) {
   if (itemType == null) {
       throw new IllegalArgumentException("null itemType");
   }
   this.itemType = Type.valueOf(itemType);
}

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

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