如果您拥有一类配置值(例如您的
Constants类),并且想要从配置(属性)文件中加载所有值,则可以创建一个小助手类并使用反射:
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");
您可以扩展代码以处理更多类型。您也可以更改它以忽略缺少的属性,而不是像现在这样失败,这样字段声明中的分配将保持不变,即是默认设置。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)