注解工作原理详解

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

而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

 

posted @ 2018-07-27 15:36  木&子  阅读(4976)  评论(1编辑  收藏  举报