java注解實現原理的理解


Java注解實際上只是對包、類、方法、成員變量等java程序進行標注。其本身沒有業務邏輯、

要實現注解相應的業務邏輯功能必須由另外的處理類來實現。

其基本原理就是通過java反射機制,獲取這些java程序的包、類、方法、成員變量的注解、然后加

以判斷並實現相應的業務功能邏輯。

 

java的內置注解包括@Override、@Deprecated、@SuppressWarnings("unchecked")等,具體的實現邏輯是由編譯器實現。

 

自定義注解只能通過@Interface關鍵字來定義、會自動繼承java.lang.annotation接口。

在自定義注解時使用元注解來表明注解的作用域以及擴展其他功能,java中一共有四個元注解。

@Retention::定義了被注解的注解的生命周期,從RetentionPolicy中取值。

          SOURCE:在源文件中有效(即源文件保留

          CLASS:在class文件中有效(即class文件中保留)

          RUNTIME:在運行時有效(即運行時保留)

@Target:用於描述注解所能修飾的對象范圍,從ElementType中取值。

          1.CONSTRUCTOR:用於描述構造器

     2.FIELD:用於描述域
     3.LOCAL_VARIABLE:用於描述局部變量
     4.METHOD:用於描述方法
     5.PACKAGE:用於描述包
     6.PARAMETER:用於描述參數
     7.TYPE:用於描述類、接口(包括注解類型) 或enum聲明

@Documented:可以讓被該注解標示的注解被如javadoc此類的工具文檔化

         生成javadoc的步驟:選中類所在的包—>project ->Generate Javadoc

         在生成的index.html中,注解信息會被文檔化

 

    JUnit3:反射實現

     JUnit4:注解+反射實現

 

=================測試======================

------------------------------------------------

 自定義注解

package test;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAnnotation {
String testAnnView() default "myview";

String value() default "default";
}

 ------------------------------------------------

 使用注解

class FieldAnn {
@MyAnnotation()
private String fieldA;

@MyAnnotation(testAnnView = "testAnnView")
private String fieldB;
}

 

 ------------------------------------------------

 實現注解邏輯

 

public class Test1 {

public static void main(String[] args) {
Class clazz = FieldAnn.class;
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
MyAnnotation myAnnotation = field.getAnnotation(MyAnnotation.class);
if (myAnnotation != null) {
System.out.println(field + ":" + field.getName() + "value:" + myAnnotation.testAnnView());
}

}
}

}

結果輸出:

 


免責聲明!

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



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