【发布时间】:2016-08-11 22:53:07
【问题描述】:
我有来自属性文件的 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();
}
}
属性文件。 message.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;
}
【问题讨论】:
-
问题是属性文件中的一切都是字符串。除非您想使用异常并手动尝试每个解析(这很糟糕),否则我看不出如何自动解析某些内容。毕竟字符串
3或false对编译器意味着什么?没什么…… -
“我不知道键和值是什么”是什么意思?你的问题不清楚
-
好吧,再想一想,如果您只想解析布尔值、整数和双精度值,使用正则表达式(用于验证和查找类型)+反射(用于填充常量)的组合是可行的。我认为这比使用异常要好一些。
-
Dambros,这可能是使用正则表达式的一种解决方案。我确实想到了为不同的原语创建不同的属性文件,然后它将是类型安全的。
-
您肯定需要关于属性数据类型的元数据in 属性文件。如果有人添加另一个属性
IS_ENABLED = true,您的逻辑会自动将其解析为boolean,但使用该属性的代码中的实际逻辑将其视为String。
标签: java constants properties-file