注解与反射的结合运用
自定义注解
@Target(ElementType.TYPE)//用在类上
@Retention(RetentionPolicy.RUNTIME)//保留至程序运行期间
public @interface MyComponent {
}
@Target(ElementType.FIELD)//用在类的属性上
@Retention(RetentionPolicy.RUNTIME)//保留至程序运行期间
public @interface MyValue {
String value();
}
编写类并加上注解
import lombok.Data;
@Data
@MyComponent
public class Dog {
@MyValue("2")
private Integer id;
@MyValue("旺财")
private String name;
}
测试
Class<Dog> dogClass = Dog.class;
MyComponent annotation = dogClass.getAnnotation(MyComponent.class);
if (annotation != null) {
//创建对象
Constructor constructor = dogClass.getConstructor(null);
Dog dog = (Dog) constructor.newInstance(null);
//开始赋值
Field[] declaredFields = dogClass.getDeclaredFields();//获取对象属性
for (Field declaredField : declaredFields) {
MyValue valueAnnotation = declaredField.getAnnotation(MyValue.class);
if (valueAnnotation != null) {
String value = valueAnnotation.value();//获取传入注解的值
declaredField.setAccessible(true);//关闭安全检查机制,暴力反射给私有属性赋值
//判断属性类型
if (declaredField.getType().getName().equals("java.lang.Integer")) {
Integer integerval = Integer.parseInt(value);
declaredField.set(dog, integerval);//通过反射给属性赋值
} else {
declaredField.set(dog, value);
}
}
}
System.out.println(dog);
} else {
System.out.println("无法创建Dog对象");
}