注解与反射的结合运用

注解与反射的结合运用

自定义注解

@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对象");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值