首页 > 解决方案 > 检查枚举结构中的值

问题描述

我使用这个 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

标签: java

解决方案


代替:

Optional.of(values())

和:

Stream.of(FeatureBitString.values())

推荐阅读