java - 如何导出映射到枚举的数据

标签 java

我有一组数据需要从Excel表格导入,举个最简单的例子。注意:数据最终可能支持上传任何区域设置。

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

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

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

最佳答案

您不需要编写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

In addition, if E is the name of an enum type, then that type has the following implicitly declared static methods:

/**

* 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);

关于java - 如何导出映射到枚举的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2996206/

相关文章:

java - 使用 JPA 将新实例添加到表中

java - Hibernate:按列名设置字段

java - 使用 jpa 持久化(或查找)对象不会保存其封装的对象列表

java - java平台下如何使用opencv计算HSV直方图?

java - 使用 Swagger 将创建的日期时间添加到 REST API

java - 为什么 SecureSocial 和 Play 2.3.2 会出现 Unresolved 依赖项错误?

Java - 接口(interface)上嵌套可参数化类型的类型变量

java - dbpedia 聚光灯数据集

java - 如何根据日期对回收者 View 进行排序

java - 无法进入下一页