java+boolean+属性,java – 从属性中获取int,float,boolean和string

如果您有一类配置值,例如常量类,并且要从配置(属性)文件加载所有值,则可以创建一个小帮手类并使用反射:

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

您可以扩展代码来处理更多类型。您还可以将其更改为忽略缺少的属性,而不是像现在那样失败,因此字段声明中的赋值将保持不变,即默认值。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值