Wil*_*Boy 113 java enums overriding tostring value-of
我的值enum
是需要在其中包含空格的单词,但枚举不能在其值中包含空格,因此它们全部聚集在一起.我想覆盖toString()
添加这些空格我告诉它.
当我使用valueOf()
添加空格的相同字符串时,我还希望枚举能够提供正确的枚举.
例如:
public enum RandomEnum
{
StartHere,
StopHere
}
Run Code Online (Sandbox Code Playgroud)
呼叫toString()
上RandomEnum
,其值是StartHere
返回字符串"Start Here"
.调用valueof()
相同的字符串("Start Here"
)返回枚举值StartHere
.
我怎样才能做到这一点?
Jug*_*hah 181
你可以试试这段代码.由于您无法覆盖valueOf
方法,因此您必须定义一个自定义方法(getEnum
在下面的示例代码中),该方法返回您需要的值并更改您的客户端以使用此方法.
public enum RandomEnum {
StartHere("Start Here"),
StopHere("Stop Here");
private String value;
RandomEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return this.getValue();
}
public static RandomEnum getEnum(String value) {
for(RandomEnum v : values())
if(v.getValue().equalsIgnoreCase(value)) return v;
throw new IllegalArgumentException();
}
}
Run Code Online (Sandbox Code Playgroud)
小智 22
试试这个,但我不确定每个地方都会有效:)
public enum MyEnum {
A("Start There"),
B("Start Here");
MyEnum(String name) {
try {
Field fieldName = getClass().getSuperclass().getDeclaredField("name");
fieldName.setAccessible(true);
fieldName.set(this, name);
fieldName.setAccessible(false);
} catch (Exception e) {}
}
}
Run Code Online (Sandbox Code Playgroud)
ped*_*rro 12
您可以在枚举中使用静态Map将字符串映射到枚举常量.在'getEnum'静态方法中使用它.这样就无需在每次想要从String值中获取枚举时遍历枚举.
public enum RandomEnum {
StartHere("Start Here"),
StopHere("Stop Here");
private final String strVal;
private RandomEnum(String strVal) {
this.strVal = strVal;
}
public static RandomEnum getEnum(String strVal) {
if(!strValMap.containsKey(strVal)) {
throw new IllegalArgumentException("Unknown String Value: " + strVal);
}
return strValMap.get(strVal);
}
private static final Map<String, RandomEnum> strValMap;
static {
final Map<String, RandomEnum> tmpMap = Maps.newHashMap();
for(final RandomEnum en : RandomEnum.values()) {
tmpMap.put(en.strVal, en);
}
strValMap = ImmutableMap.copyOf(tmpMap);
}
@Override
public String toString() {
return strVal;
}
}
Run Code Online (Sandbox Code Playgroud)
只需确保地图的静态初始化发生在枚举常量的声明之下.
顺便说一句 - 'ImmutableMap'类型来自Google guava API,我肯定会在这样的情况下推荐它.
编辑 - 根据评论:
lrn*_*grm 12
Java 8实现怎么样?(null可以替换为您的默认枚举)
public static RandomEnum getEnum(String value) {
List<RandomEnum> list = Arrays.asList(RandomEnum.values());
return list.stream().filter(m -> m.value.equals(value)).findAny().orElse(null);
}
Run Code Online (Sandbox Code Playgroud)
或者您可以使用:
...findAny().orElseThrow(NotFoundException::new);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
133174 次 |
最近记录: |