栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从属性获取整数,浮点数,布尔值和字符串

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从属性获取整数,浮点数,布尔值和字符串

如果您拥有一类配置值(例如您的

Constants
类),并且想要从配置(属性)文件中加载所有值,则可以创建一个小助手类并使用反射:

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");

您可以扩展代码以处理更多类型。您也可以更改它以忽略缺少的属性,而不是像现在这样失败,这样字段声明中的分配将保持不变,即是默认设置。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/410672.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号