假设我有一个枚举
public enum Blah {
A, B, C, D
}
我想找到一个字符串的枚举值,例如“a”,它将是Blah.a。如何做到这一点?
Enum.valueOf()是我需要的方法吗?如果是,我将如何使用它?
假设我有一个枚举
public enum Blah {
A, B, C, D
}
我想找到一个字符串的枚举值,例如“a”,它将是Blah.a。如何做到这一点?
Enum.valueOf()是我需要的方法吗?如果是,我将如何使用它?
当前回答
如果您不想编写自己的实用程序,请使用Google的番石榴库:
Enums.getIfPresent(Blah.class, "A")
与内置Java函数不同,它让您检查Blah中是否存在A,并且不会引发异常。
其他回答
我的两分钱在这里:使用Java 8 Streams并检查精确的字符串:
public enum MyEnum {
VALUE_1("Super"),
VALUE_2("Rainbow"),
VALUE_3("Dash"),
VALUE_3("Rocks");
private final String value;
MyEnum(String value) {
this.value = value;
}
/**
* @return the Enum representation for the given string.
* @throws IllegalArgumentException if unknown string.
*/
public static MyEnum fromString(String s) throws IllegalArgumentException {
return Arrays.stream(MyEnum.values())
.filter(v -> v.value.equals(s))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("unknown value: " + s));
}
}
我将函数重命名为fromString(),因为使用该约定命名它,您将从Java语言本身获得一些好处;例如:
在HeaderParam注释处直接转换类型
如果文本与枚举值不同,则另一种解决方案:
public enum Blah {
A("text1"),
B("text2"),
C("text3"),
D("text4");
private String text;
Blah(String text) {
this.text = text;
}
public String getText() {
return this.text;
}
public static Blah fromString(String text) {
for (Blah b : Blah.values()) {
if (b.text.equalsIgnoreCase(text)) {
return b;
}
}
return null;
}
}
我正在寻找一个答案来查找“blah”名称,而不是其值(而不是文本)。根据马努的回答,我发现这段代码很有用:
public enum Blah {
A("text1"),
B("text2"),
C("text3"),
D("text4");
private String text;
Blah(String text) {
this.text = text;
}
public String getText() {
return this.text;
}
public static Blah valueOfCode(String blahCode) throws IllegalArgumentException {
Blah blah = Arrays.stream(Blah.values())
.filter(val -> val.name().equals(blahCode))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Unable to resolve blah: " + blahCode));
return blah;
}
}
public enum DivisionType {
DEFAULT(0){
@Override
public void sort(List<SigInUserDto> SigInUserDtos) {
SigInUserDtos.sort(new SigInUserCoinsQueueComparator());
}
},
ASSIGNPOINTS(1) {
@Override
public void sort(List<SigInUserDto> SigInUserDtos) {
SigInUserDtos.sort(new SigInUserPointsComparator());
}
},
ASSIGNEVENORDER(2) {
@Override
public void sort(List<SigInUserDto> SigInUserDtos) {
SigInUserDtos.sort(new SigInUserOrderCountComparator());
}
};
public final Integer label;
DivisionType(Integer label) {
this.label = label;
}
public static DivisionType getTypeById(Integer id) {
for (DivisionType value : DivisionType.values()) {
if (value.label == id) {
return value;
}
}
return DEFAULT;
}
public abstract void sort(List<SigInUserDto> SigInUserDtos);
}
使用枚举:DivisionType.getTypeById(object.getBalancingTypesId().intValue()).sort(sigInUserDtoList);
在这里,sort()函数在每个枚举匹配下实现(重载)。因此,基于对象“object.getBalancingTypesId().intValue()”匹配值,调用并排序特定的枚举匹配。
你也应该小心处理你的案子。让我解释一下:Blah.valueOf(“A”)有效,但Blah.valueOf(“A”)无效。然后Blah.valueOf(“a”.toUpperCase(Locale.ENGLISH))也会起作用。
在Android上,你应该使用Locale.US,正如苏拉指出的那样。