程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

Spring 注解中反射的应用

发布于2021-05-29 21:20     阅读(1290)     评论(0)     点赞(17)     收藏(0)


springboot web 项目中

@Data
@Component
public class Cat {
    @Value("1")
    private int id;
    @Value("小花猫")
    private String name;
}
@SpringBootApplication
public class App {
    public static void main(String[] args) {
       ApplicationContext run =  SpringApplication.run(App.class);
        System.out.println(run.getBean(Cat.class));
    }
}

启动程序: 输出如下
在这里插入图片描述

添加@ComponetValue 实现bean 的创建和属性值的注入。

注解本身不会实现这些功能,只是一个标志。

下面来自定义注解,实现 上述功能

自定义MyValueMyComponet

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyValue {
    String value() default "";
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface MyComponent {
    String value() default "";
}
@Data
@MyComponent
public class Dog {
    @MyValue("2")
    private Integer id;
    @MyValue("旺财")
    private String name;
}

核心代码

public class Test2 {
    public static void main(String[] args) throws InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchMethodException {
        Class<Dog> dogClass = Dog.class;
        MyComponent annotation = dogClass.getAnnotation(MyComponent.class);
        if (annotation !=null ){
            //System.out.println("dogClass 添加了Mycomponet 注解");
            Constructor<Dog> constructor = dogClass.getConstructor(null);
            //创建 dog 实例对象
            Dog dog = constructor.newInstance(null);

            //开始赋值,获取类本身的所有属性方法
            Field[] fields = dogClass.getDeclaredFields();

            for (Field  field : fields) {
                // System.out.println(field); //打印输出属性
                MyValue valueAnno = field.getAnnotation(MyValue.class);
                if(valueAnno != null){
                   // System.out.println("filed 添加了 MyValue 注解");
                    //获取注解的值
                    String value = valueAnno.value();
                   // System.out.println(field + "注解值为"  + value);
                    //把值赋值给对象的属性的值
                    //暴力反射开启 可以给添加了private 属性值赋值
                    field.setAccessible(true);
                    //判断属性类型
                    if(field.getType().getName().equals("java.lang.Integer")){
                        Integer val = Integer.parseInt(value);
                        field.set(dog,val);
                    }else{
                        field.set(dog,value);
                    }


                }

            }
            System.out.println(dog);

        }else{
            System.out.println("无法创建对象");
        }
    }
}

启动代码:
在这里插入图片描述



所属网站分类: 技术文章 > 博客

作者:coding

链接:http://www.javaheidong.com/blog/article/207320/6384e2fa3fb3ab3d610f/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

17 0
收藏该文
已收藏

评论内容:(最多支持255个字符)