Java中Properties对象的使用

Properties是Java中jdk自带的一个对象

import java.util.Properties;

我们可以直接将后缀为properties的文件变为Properties对象,然后通过Porperties对象中的

public synchronized Object setProperty(String key, String value)
public String getProperty(String key)
等方法对对象进行操作。

.properties文件:



将文件中的数据变为properties对象:

 Properties properties = new Properties();
 try (FileInputStream fis = new FileInputStream(path)) {
        properties.load(fis);
 } catch (IOException e) {
        throw new RuntimeException("flyusercenter加载配置失败", e);
 }

load方法就是具体的转换过程,properties自带的。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以在自定义注解的时候,使用@Retention(RetentionPolicy.RUNTIME)注解来指定注解的生命周期为运行时,然后通过反射获取被注解的元素,进而获取注解参数的属性值。例如,假设你有一个自定义注解 @Config,其包含 key 和 value 两个属性,你可以在注解添加一个属性名为 value 的 String 类型的属性,用来接收 properties 对象的属性值,代码示例如下: ```java @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface Config { String key() default ""; String value() default ""; } ``` 然后在需要使用注解的类使用 @Config 注解标注需要接收 properties 对象属性值的字段,例如: ```java public class MyClass { @Config(key = "myProperty") private String myField; } ``` 最后,通过反射获取 MyClass 类被 @Config 注解标注的字段,读取其的 key 属性值,然后从 properties 对象获取对应的属性值,将其设置到被注解的字段上即可,例如: ```java Properties props = new Properties(); props.load(new FileInputStream("config.properties")); MyClass obj = new MyClass(); Field[] fields = obj.getClass().getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Config.class)) { Config config = field.getAnnotation(Config.class); String key = config.key(); String value = props.getProperty(key); field.setAccessible(true); field.set(obj, value); } } ``` 这样,就可以通过注解的方式接收 properties 对象的属性值了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值