java - 检查枚举结构中的值
问题描述
我使用这个 JUnit 测试从数据库中加载值并将它们保存回来。到目前为止,这是当前的实现:
public class BitStringTest {
Map<FeatureBitString, Boolean> features = new HashMap<>();
public void enableFeature(FeatureBitString feature) {
features.put(feature, true);
}
public void disableFeature(FeatureBitString feature) {
features.put(feature, false);
}
public boolean isFeatureEnabled(FeatureBitString feature) {
Boolean enabled = features.get(feature);
return enabled != null && enabled;
}
public String convertToDatabaseValue() {
return Arrays.stream(FeatureBitString.values()).map(f -> isFeatureEnabled(f) ? "1" : "0").collect(joining());
}
public Map<FeatureBitString, Boolean> initFromDatabaseValue(String bitString) {
// Note that, bitString length should equals to your number of feature. Or you
// have to padding it
char[] bitArray = bitString.toCharArray();
return Arrays.stream(FeatureBitString.values())
.collect(toMap(f -> f, f -> bitArray[f.getIndex()] == '1', (v1, v2) -> v2, LinkedHashMap::new));
}
@Test
public void testToDatabaseValue() {
System.out.println("\nProducing Features ");
features.put(FeatureBitString.A, true);
features.put(FeatureBitString.F, true);
Assertions.assertEquals(convertToDatabaseValue(), "1000010");
}
}
enum FeatureBitString {
A("Type1", 0), // index 0 in bit string
B("Type2", 1), // index 1 in bit String
C("Type3", 2), // index 2 in bit String
D("Type3", 3), // index 3 in bit String
E("Type4", 4), // index 4 in bit String
F("Type5", 5), // index 5 in bit String
G("Type6", 6); // index 6 in bit String
private final String featureName;
private final int index;
private FeatureBitString(String featureName, int value) {
this.featureName = featureName;
this.index = value;
}
public String getFeatureName() {
return featureName;
}
public int getIndex() {
return index;
}
}
我如何验证枚举 FeatureBitString 中是否存在值“Type2”?在我加载它之前,我想根据枚举数据检查这个值是否存在。
我尝试使用此代码:
public static Optional<FeatureBitString> getByFeatureName(String featureName) {
return Optional.of(values()).map(FeatureBitString::getFeatureName).filter(f -> f.equals(featureName)).findAny();
}
if (FeatureBitString.getByFeatureName("Type2").isPresent()) {
// ...
}
但我得到错误method values() is undefined for the type DatabaseFeaturesBitStringTest
解决方案
代替:
Optional.of(values())
和:
Stream.of(FeatureBitString.values())
推荐阅读
- zurb-foundation - 基础框架中柱间距如何调整?
- javascript - 解析和格式化字符串中的日期
- powershell - 在 PowerShell v2.0 中将文件压缩为 .ZIP
- apache-nifi - 惩罚流文件导致后续处理器累积任务/时间
- javascript - 谷歌地图的 css 覆盖了我自己的样式,我该如何防止呢?
- sockets - socket.io 加载资源失败:net::ERR_TIMED_OUT
- reactjs - 如何制作类似 Material UI 的 Gmail 任务工具栏
- python - pyinstaller 中的 sys.stdin.readlines()
- php - 如何在单页视图上执行一次 php 代码
- javascript - React Loadable 不会在浏览器刷新时更新