歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java自定義注解

Java自定義注解

日期:2017/3/1 10:09:54   编辑:Linux編程

一、什麼是注釋

說起注釋,得先提一提什麼是元數據(metadata)。所謂元數據就是數據的數據。也就是說,元數據是描述數據的。就象數據表中的字段一樣,每個字段描述了這個字段下的數據的含義。而J2SE5.0中提供的注釋就是java源代碼的元數據,也就是說注釋是描述java源代碼的。在J2SE5.0中可以自定義注釋。使用時在@後面跟注釋的名字。

二、J2SE5.0中預定義的注釋

在J2SE5.0的java.lang包中預定義了三個注釋。它們是Override、Deprecated和SuppressWarnings。下面分別解釋它們的含義。

1.Override注釋:僅用於方法(不可用於類、包的生命或其他),指明注釋的方法將覆蓋超類中的方法(如果覆蓋父類的方法而沒有注

釋就無法編譯該類),注釋還能確保注釋父類方法的拼寫是正確(錯誤的編寫,編譯器不認為是子類的新方法,而會報錯)

2.@Deprecated注釋:對不應再使用的方法進行注釋,與正在聲明為過時的方法放在同一行。使用被 Deprecated注釋的方法,編譯器會

提示方法過時警告(”Warring”)

3.@SuppressWarnings注釋:單一注釋,可以通過數組提供變量,變量值指明要阻止的特定類型警告(忽略某些警告)。數組中的變量指明要阻止的警告@SuppressWarnings(value={”unchecked”,”fallthrough”}))

三、自定義注釋@interface

  1. @Retention(RetentionPolicy.RUNTIME)
  2. public @interface LogClass
  3. {
  4. String type() default "";
  5. String comments() default "";
  6. }

  1. @Retention(RetentionPolicy.RUNTIME)
  2. public @interface Anno {
  3. String name() default "zhangsan";
  4. }

自定義注解使用類:

  1. @Anno(name="ttttttt")
  2. public class AnnotationImpl {
  3. @LogClass()
  4. public String getName() {
  5. return "aaaa";
  6. }
  7. @LogClass(comments="cccccc")
  8. public String getValue() {
  9. return "bbbb";
  10. }
  11. }

測試:

  1. public static void main(String[] args) throws Exception {
  2. Class<?> clazz = Class
  3. .forName("com.ronghai.hfms.support.upload.AnnotationImpl");
  4. Method[] method = clazz.getMethods();
  5. boolean flag = clazz.isAnnotationPresent(Anno.class);
  6. if (flag) {
  7. Anno first = (Anno) clazz.getAnnotation(Anno.class);
  8. System.out.println("Annotation:" + first.name());
  9. }
  10. for (int i = 0; i < method.length; i++) {
  11. LogClass log=method[i].getAnnotation(LogClass.class);
  12. if(log!=null){
  13. System.out.println(1+i+"、"+log.comments());
  14. }
  15. }
  16. }

輸出結果:

Annotation:ttttttt
1、
2、cccccc

@Target:指定程序元定義的注釋所使用的地方,它使用了另一個類:ElementType,是一個枚舉類定義了注釋類型可以應用到不同的程序元素以免使用者誤用。

  1. public enum ElementType {
  2. /** Class, interface (including annotation type), or enum declaration */
  3. TYPE,
  4. /** Field declaration (includes enum constants) */
  5. FIELD,
  6. /** Method declaration */
  7. METHOD,
  8. /** Parameter declaration */
  9. PARAMETER,
  10. /** Constructor declaration */
  11. CONSTRUCTOR,
  12. /** Local variable declaration */
  13. LOCAL_VARIABLE,
  14. /** Annotation type declaration */
  15. ANNOTATION_TYPE,
  16. /** Package declaration */
  17. PACKAGE
  18. }

@Retention:這個元注釋和java編譯器處理注釋的注釋類型方式相關,告訴編譯器在處理自定義注釋類型的幾種不同的選擇,需要使用RetentionPolicy枚舉類。此枚舉類只有一個成員變量,可以不用指明成名名稱而賦值,看Retention的源代碼:

  1. public enum RetentionPolicy {
  2. SOURCE,
  3. CLASS,
  4. RUNTIME
  5. }
@Documented:是一個標記注釋,表示注釋應該出現在類的javadoc中,因為在默認情況下注釋時不包括在javadoc中的。
Copyright © Linux教程網 All Rights Reserved