java+boolean+属性,java – 从属性中获取int,float,boolean和string
如果您有一類配置值,例如常量類,并且要從配置(屬性)文件加載所有值,則可以創建一個小幫手類并使用反射:
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");
您可以擴展代碼來處理更多類型。您還可以將其更改為忽略缺少的屬性,而不是像現在那樣失敗,因此字段聲明中的賦值將保持不變,即默認值。
總結
以上是生活随笔為你收集整理的java+boolean+属性,java – 从属性中获取int,float,boolean和string的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python的内存回收机制_关于pyth
- 下一篇: android oat如何提取dex文件