java 注解接收properties对象
时间: 2023-11-24 09:19:37 浏览: 29
你可以在自定义注解的时候,使用@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 对象中的属性值了。