【问题标题】:How to export data which are mapped to enumerations如何导出映射到枚举的数据
【发布时间】:2010-06-08 09:42:29
【问题描述】:

我有一组数据需要从 Excel 表中导入,让我们举个最简单的例子。注意:数据最终可能支持上传任何语言环境。

例如假设表示用户的字段之一是性别映射到枚举并存储在数据库中,0 表示男性,1 表示女性。 0 和 1 是短值。

如果我必须导入我不能指望用户输入数字的值(因为它们不直观并且当枚举更大时很麻烦),映射到枚举的正确方法是什么。

我们是否应该要求他们在这些情况下(例如男性或女性)提供一个字符串值,并通过编写方法 public static Gender Gender.fromString(String value) 在我们的代码中提供对枚举的转换

【问题讨论】:

    标签: java


    【解决方案1】:

    你不需要写fromStringenum 类型已经有一个static valueOf(String)

    public class EnumValueOf {
        enum Gender {
            MALE, FEMALE;
        }
        public static void main(String[] args) {
            Gender g = Gender.valueOf("MALE");
            System.out.println(g);
            // prints "MALE"
            System.out.println(g == Gender.MALE);
            // prints "true"
        }
    }
    

    规范

    它有些隐藏,但这是在 JLS 中指定的。

    JLS 8.9 Enums

    此外,如果Eenum 类型的名称,则该类型具有以下隐式声明的static 方法:

    /**
    
    * Returns an array containing the constants of this enum 
    * type, in the order they're declared.  This method may be
    * used to iterate over the constants as follows:
    *
    *    for(E c : E.values())
    *        System.out.println(c);
    *
    * @return an array containing the constants of this enum 
    * type, in the order they're declared
    */
    public static E[] values();
    
    /**
    * Returns the enum constant of this type with the specified
    * name.
    * The string must match exactly an identifier used to declare
    * an enum constant in this type.  (Extraneous whitespace 
    * characters are not permitted.)
    * 
    * @return the enum constant with the specified name
    * @throws IllegalArgumentException if this enum type has no
    * constant with the specified name
    */
    public static E valueOf(String name);
    

    【讨论】:

      【解决方案2】:

      提供静态方法对我来说很好。然后,您在应用程序中有一个点,您关心从用户输入到 Gender 对象的转换。

      正如你提到的本地化,第二种方法

      public static Gender Gender.fromString(String value, Locale locale);
      

      可能是个好主意。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-14
        • 1970-01-01
        • 2011-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-13
        相关资源
        最近更新 更多