检查枚举结构中的值

时间:2019-04-04 07:39:55

标签: 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

1 个答案:

答案 0 :(得分:2)

替换:

Optional.of(values())

使用:

Stream.of(FeatureBitString.values())