标签:
import java.util.ResourceBundle;
import org.springframework.util.NumberUtils;
/**读取资源文件的工具类.
*/
public class ConfigUtil {
/**读取资源文件中的键值信息.
* 例如有键值名为a,其对应的值为整数类型,那么方法即为:readConfigForObject("a",Integer.class).
* @param keyName 键值名
* @param requiredType 返回数据类型
* @return 指定的数据类型返回值或异常时返回null
* @version v1.0.0
*/
@SuppressWarnings("unchecked")
public static <T> T readConfigForObject(String keyName,Class<T> requiredType){
try {
ResourceBundle rb = ResourceBundle.getBundle("config");
Object object = rb.getObject(keyName);
return (T) convertValueToRequiredType(object,requiredType);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return null;
}
/**把指定的参数值转换成指定数据类型对应的值
* @param value 待转换的参数值
* @param requiredType 数据类型
* @return 指定数据类型对应的值
* @version v1.0.0
*/
@SuppressWarnings("unchecked")
protected static Object convertValueToRequiredType(Object value, Class requiredType) {
if (String.class.equals(requiredType)) {
return value.toString();
} else if (Number.class.isAssignableFrom(requiredType)) {
if (value instanceof Number) {
// Convert original Number to target Number class.
return NumberUtils.convertNumberToTargetClass(((Number) value), requiredType);
}
else {
// Convert stringified value to target Number class.
return NumberUtils.parseNumber(value.toString(), requiredType);
}
} else if(Boolean.class.equals(requiredType)) {
return Boolean.valueOf(value.toString());
} else {
throw new IllegalArgumentException(
"Value [" + value + "] is of type [" + value.getClass().getName() +
"] and cannot be converted to required type [" + requiredType.getName() + "]");
}
}
}
标签:
原文地址:http://blog.csdn.net/u011328015/article/details/44302165