【发布时间】:2018-12-28 02:15:14
【问题描述】:
我已经使用java.util.Properties 向我的应用程序添加了一个人类可读的配置文件,并尝试在它周围添加一个包装器以使类型转换更容易。具体来说,我希望返回的值从提供的默认值“继承”它的类型。到目前为止,这是我所得到的:
protected <T> T getProperty(String key, T fallback) {
String value = properties.getProperty(key);
if (value == null) {
return fallback;
} else {
return new T(value);
}
}
getProperty("foo", true) 的返回值将是一个布尔值,无论它是否是从属性文件中读取的,对于字符串、整数、双精度数等也是如此。当然,上面的 sn -p 并没有真正编译:
PropertiesExample.java:35: unexpected type
found : type parameter T
required: class
return new T(value);
^
1 error
是我做错了,还是我只是想做一些不能做的事情?
编辑:用法示例:
// I'm trying to simplify this...
protected void func1() {
foobar = new Integer(properties.getProperty("foobar", "210"));
foobaz = new Boolean(properties.getProperty("foobaz", "true"));
}
// ...into this...
protected void func2() {
foobar = getProperty("foobar", 210);
foobaz = getProperty("foobaz", true);
}
【问题讨论】: