注解工作原理詳解


我們自定義的注解其實不會發揮作用,很好明白的,因為我們的注解只是名字具有我們所需要的作用,換句話說,我們可以命名為任何名字,這個時候就無法確定注解的功能了。

而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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM