java - 在java8中验证属性文件中的 key 的最佳方法

标签 java

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

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

我的枚举:

public enum VersionEnum {
A,
B,
C,
D

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

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

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

任何帮助将不胜感激。

最佳答案

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

查看带有注释的示例代码(如果您不喜欢阅读,请向下移动Stream 解决方案)。
对于 key ,我们可以使用 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 here 上玩它.

关于java - 在java8中验证属性文件中的 key 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55509645/

相关文章:

带有一个日期和可选的第二个日期的文件名的 Java 正则表达式

java - 使用 OpenOffice API 抓取整个文档树

Java HashSet 与 HashMap

java - 如何在 OSGI (Apache Felix) 中为别人的 bundle 实现 AOP?

java - 不明确的方法调用 println char 数组和 String(而不是 Object)

java - Spring 云任务

java - 在 Java 中扩展类时重载方法

java - HTTP 响应代码 : expected time between informational code (1xx) and non-informational code

java - 在ant中设置SonarQube的JDK路径

java - 在 Eclipse 中恢复旧版本的构建路径