我有一组数据需要从Excel表格导入,举个最简单的例子。注意:数据最终可能支持上传任何区域设置。
例如假设表示用户的字段之一的性别映射到枚举,并在数据库中存储为 0 代表男性,1 代表女性。 0 和 1 是短值。
如果我必须导入值,我不能指望用户输入数字(因为它们不直观,并且当枚举较大时很麻烦),映射到枚举的正确方法是什么。
我们是否应该要求他们在这些情况下提供一个字符串值(例如男性或女性),并通过编写方法 public static Gender Gender.fromString(String value) 在我们的代码中提供对枚举的转换
最佳答案
您不需要编写fromString
; enum
类型已经有一个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 anenum
type, then that type has the following implicitly declaredstatic
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/