zoukankan      html  css  js  c++  java
  • 注解工作原理详解

    我们自定义的注解其实不会发挥作用,很好明白的,因为我们的注解只是名字具有我们所需要的作用,换句话说,我们可以命名为任何名字,这个时候就无法确定注解的功能了。

    而java自带的注解(jdk1.5开始才有注解)另外有一套代码来确定这个注解的作用,那么下面我们就自己来写这套代码,来实现自己所定义的注解的作用(需要用到反射知识)

    下面是一个普通的注解作用是给成员变量赋默认值

    package ReasonTest;
    
    import java.lang.annotation.Documented;
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Inherited;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;
    
    @Target(ElementType.FIELD)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Inherited
    public @interface Autowired {
    
    }

    下面是使用这个注解的一个类,如果没有reflect方法,date为null  但是现在date是有时间的。

    package ReasonTest;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    public class LoginService {
    
        @Autowired
        public static Date date;
        
        public static void login() {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd hh-mm-ss");
            String result = sdf.format(date);
            System.out.println(result);
        }
        
        public static void main(String[] args) {
            Reflect.reflect(LoginService.class);
            login();
        }
    }

    不报空指针错误就是因为Reflect.reflect(LoginService.class);的执行,这行代码用反射的方法给date赋予了初始值

    package ReasonTest;
    
    import java.lang.annotation.Annotation;
    import java.lang.reflect.Field;
    import java.lang.reflect.Type;
    
    public class Reflect {
    
        public static void reflect(Class clazz) {
            Field [] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                Annotation [] annotations = field.getAnnotations();
                for (Annotation annotation : annotations) {
                    if(annotation instanceof Autowired) {
                        Class type = (Class)field.getGenericType();
                        try {
                            field.set(clazz.newInstance(),type.newInstance() );
                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        } catch (InstantiationException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    至此,我们就完成了@Autowired的作用,如有任何疑问,欢迎提出0.0

  • 相关阅读:
    Spring Boot 详细简介
    Linux 安装 MySQL 8 数据库(图文详细教程)
    有了这个日期工具类,让日期转化不再烦恼
    Linux常用实用命令
    Java分割中英文,并且中文不能分割一半?
    Spring MVC或Spring Boot配置默认访问页面不生效?
    js如何判断当前页面是否处于激活状态
    博客园 & 陌上花开HIMMR | 脱单倒计时!只能帮你到这了
    博客园 & 陌上花开HIMMR | 距2020年脱单,只剩34天!
    博客园 & 陌上花开HIMMR | 脱单倒计时!刚过完10.24的你,还想一个人过11.11吗?
  • 原文地址:https://www.cnblogs.com/lyxcode/p/9377897.html
Copyright © 2011-2022 走看看