我有属性文件中的 int、float、boolean 和 string。一切都已加载到属性中。目前,我正在解析值,因为我知道特定键的预期值。
Boolean.parseBoolean("false");
Integer.parseInt("3")
设置这些常量值的更好方法是什么,如果我不知道键的原始值数据类型是什么。
public class Messages {
Properties appProperties = null;
FileInputStream file = null;
public void initialization() throws Exception {
appProperties = new Properties();
try {
loadPropertiesFile();
} catch (Exception e) {
throw new Exception(e.getMessage(), e);
}
}
public void loadPropertiesFile() throws IOException {
String path = "./cfg/message.properties";
file = new FileInputStream(path);
appProperties.load(file);
file.close();
}
}
属性文件。消息.properties
SSO_URL = https://example.com/connect/token
SSO_API_USERNAME = test
SSO_API_PASSWORD = Uo88YmMpKUp
SSO_API_SCOPE = intraday_api
SSO_IS_PROXY_ENABLED = false
SSO_MAX_RETRY_COUNT = 3
SSO_FLOAT_VALUE = 3.0
常数.java
public class Constants {
public static String SSO_URL = null;
public static String SSO_API_USERNAME = null;
public static String SSO_API_PASSWORD = null;
public static String SSO_API_SCOPE = null;
public static boolean SSO_IS_PROXY_ENABLED = false;
public static int SSO_MAX_RETRY_COUNT = 0;
public static float SSO_FLOAT_VALUE = 0;
}
原文由 Pratiyush Kumar Singh 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果你有一类配置值,比如你的
Constants
类,并且你想从配置(属性)文件中加载所有值,你可以创建一个小帮助类并使用反射:然后你这样称呼它:
您可以扩展代码以处理更多类型。您还可以更改它以忽略缺少的属性,而不是像现在这样失败,这样字段声明中的分配将保持不变,即默认。