如果您有一类配置值,例如常量类,并且要从配置(属性)文件加载所有值,则可以创建一个小帮手类并使用反射:
public class ConfigLoader {
public static void load(Class> configClass, String file) {
try {
Properties props = new Properties();
try (FileInputStream propStream = new FileInputStream(file)) {
props.load(propStream);
}
for (Field field : configClass.getDeclaredFields())
if (Modifier.isStatic(field.getModifiers()))
field.set(null, getValue(props, field.getName(), field.getType()));
} catch (Exception e) {
throw new RuntimeException("Error loading configuration: " + e, e);
}
}
private static Object getValue(Properties props, String name, Class> type) {
String value = props.getProperty(name);
if (value == null)
throw new IllegalArgumentException("Missing configuration value: " + name);
if (type == String.class)
return value;
if (type == boolean.class)
return Boolean.parseBoolean(value);
if (type == int.class)
return Integer.parseInt(value);
if (type == float.class)
return Float.parseFloat(value);
throw new IllegalArgumentException("Unknown configuration value type: " + type.getName());
}
}
那么你这样称呼:
ConfigLoader.load(Constants.class, "/path/to/constants.properties");
您可以扩展代码来处理更多类型。您还可以将其更改为忽略缺少的属性,而不是像现在那样失败,因此字段声明中的赋值将保持不变,即默认值。