首页 > 解决方案 > 在java8中验证属性文件中的键的最佳方法

问题描述

我有一个属性文件,我需要针对一组键和值进行验证。这样用户就不能在属性文件中提供任何匿名键或无效值。

我已经通过读取属性文件并创建ENUM所有可能的键来完成它,并在流的帮助下使用枚举中提到的属性文件验证每个键。

我的枚举:

public enum VersionEnum {
A,
B,
C,
D

public static Stream<VersionEnum> stream() {
        return Arrays.stream(VersionEnum.values());
    }
}

然后运行另一个循环来比较每个键的值。

我想知道在java中是否有更好的方法来完成这个?

任何帮助将不胜感激。

标签: java

解决方案


恕我直言,更好的方法(因为不存在最好的方法)是维护存储在另一个文件中的一组默认属性。Enum对于这种任务来说,硬编码听起来太“奇怪”了。

请参阅带有注释的示例代码(如果您不喜欢阅读,请移至解决Stream方案)。
对于键,我们可以使用Properties#keySet()

// Load default/allowed properties from a resource file
final Properties allowed = new Properties();
properties.load(allowedInput);

// Load user-defined properties from a file
final Properties userDefined = new Properties();
properties.load(userDefinedInput);

// Remove all the keys from the user-defined Property
// that match with the allowed one. 
final Collection<Object> userDefinedCopy = new HashSet<>(userDefined.keySet());
userDefinedCopy.removeAll(allowed.keySet());

// If the key Set is not empty, it means the user added
// invalid or not allowed keys
if (!userDefined.isEmpty()) {
    // Error!
}

Properties#values()如果顺序或与键的关联不重要,则可以对带有 的值采用相同的方法。

final Collection<Object> allowedValues = allowed.values();
final Collection<Object> userDefinedValues = userDefined.values();
userDefinedValues.removeAll(allowedValues);

if (!userDefinedValues.isEmpty()) {
    // Error!
}

在这种情况下,我们不必创建额外的Collection<T>,因为 Properties 正在为我们做这件事

@Override
public Collection<Object> values() {
    return Collections.synchronizedCollection(map.values(), this);
}

甚至,一个Stream解决方案,如果键值关联很重要

final Properties allowed = new Properties();
// Load

final Properties userDefined = new Properties();
// Load

final long count =
    userDefined.entrySet()
               .stream()
               .filter(e -> {
                  final Object o = allowed.get(e.getKey());

                  // If 'o' is null, the user-defined property is out of bounds.
                  // If 'o' is present ('o' represents the valid value), but it doesn't
                  // match with the user-defined value, the property is wrong

                  return o == null || !Objects.equals(o, e.getValue());
               }).count();

if (count != 0) {
   // Error!
}

您可以在此处的 Ideone.com 上使用它。


推荐阅读