Java基礎——註解

1. 引言

註解@interface不是接口是註解類,在jdk1.5之後加入的功能,使用@interface自定義註解時,自動繼承了java.lang.annotation.Annotation接口。
在定義註解時,不能繼承其他的註解或接口。@interface用來聲明一個註解,其中的每一個方法實際上是聲明瞭一個配置參數。方法的名稱就是參數的名稱,返回值類型就是參數的類型(返回值類型只能是基本類型、Class、String、enum)。可以通過default來聲明參數的默認值。
在Java API文檔中特意強調了如下內容:
Annotation是所有註釋類型的公共擴展接口。注意,手動擴展這個接口並不定義註釋類型。還要注意,這個接口本身並不定義註釋類型。註釋類型的更多信息可以在Java™語言規範的9.6節。

2. 語法規範

我們以spring中的@component註解爲例,其格式如下所示

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {

	String value() default "";

}

其中主要包括四個部分

2.1 繼承的Annotation父接口

public interface Annotation {

    boolean equals(Object obj);

    int hashCode();

    String toString();

    Class<? extends Annotation> annotationType();
}

2.2 @Target中的參數ElementType

public enum ElementType {
    TYPE,               /* 類、接口(包括註釋類型)或枚舉聲明  */

    FIELD,              /* 字段聲明(包括枚舉常量)  */

    METHOD,             /* 方法聲明  */

    PARAMETER,          /* 參數聲明  */

    CONSTRUCTOR,        /* 構造方法聲明  */

    LOCAL_VARIABLE,     /* 局部變量聲明  */

    ANNOTATION_TYPE,    /* 註釋類型聲明  */

    PACKAGE             /* 包聲明  */
}

2.3 @Retention中的參數RetentionPolicy

public enum RetentionPolicy {
    SOURCE,            /* Annotation信息僅存在於編譯器處理期間,編譯器處理完之後就沒有該Annotation信息了  */

    CLASS,             /* 編譯器將Annotation存儲於類對應的.class文件中。默認行爲  */

    RUNTIME            /* 編譯器將Annotation存儲於class文件中,並且可由JVM讀入 */
}

2.4 成員變量

以無形參的方法形式來聲明Annotation的成員變量,方法名和返回值定義了成員變量名稱和類型。使用default關鍵字設置默認值,沒設置默認值的變量則使用時必須提供,有默認值的變量使用時可以設置也可以不設置。

//定義帶成員變量註解MyTag
@Rentention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyTag{
  //定義兩個成員變量,以方法的形式定義
  String name();
  int age() default 20;
}

//使用
public class Test{
  @MyTag(name="test")
  public void info(){}
}

3. 獲取註解信息

可以通過反射的方式獲取註解在某個元素上的註解和其中的值,在Java反射類庫reflect中,Class類實現了AnnotatedElement接口,其中包含多個獲取annotation的方法

package java.lang.reflect;

    boolean isAnnotationPresent(Class<? extends Annotation> annotationClass);

    <T extends Annotation> T getAnnotation(Class<T> annotationClass);
    //這個方法檢測其參數是否是可重複的註釋類型(JLS 9.6),如果是,則嘗試通過“查看”容器註釋來查找該類型的一個或多個註釋。
    //該方法的調用者可以自由地修改返回的數組;它對返回給其他調用者的數組沒有影響。
    <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass);

    Annotation[] getAnnotations();

    //如果直接存在指定類型的註釋,則返回該元素的註釋,否則爲空。此方法忽略繼承的註釋。
    <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass);
    //與上面相同,考慮可重複的註釋類型
    <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass);

    //如果直接存在指定類型的註釋,則返回該元素的註釋,否則爲空。此方法忽略繼承的註釋。
    Annotation[] getDeclaredAnnotations();

3.1 使用場景——框架初始化過程中遞歸獲取註解以及註解的註解

/**
 * 遞歸搜索所有的註解,模擬框架搜索註解過程,以當前的類註解爲例
 */
@Component
public class SearchMetaAnnations {
  public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
    List<String> test = new ArrayList<>();
    Annotation[] annotations = SearchMetaAnnations.class.getAnnotations();
    Set<Annotation> set = new HashSet<>();
    for (Annotation annotation : annotations){
      recursivelyAnnotaion(annotation,set);
    }
    System.out.println(set);
  }

  //遞歸獲取註解的註解
  public static void recursivelyAnnotaion(Annotation annotation, Set<Annotation> set){
    //通過set元素唯一的特點來實現遞歸搜索所有的註解
    if (set.add(annotation)){
      //獲取註解的註解數組
      if (annotation.annotationType().getAnnotations().length > 0){
        //搜索子註解
        for (Annotation childAnnotation : annotation.annotationType().getAnnotations()){
          recursivelyAnnotaion(childAnnotation,set);
        }

      }
      System.out.println(annotation.annotationType().getName());
    }

  }
}

3.2 使用場景——框架初始化過程中模擬掃描jar包和文件夾中的所有註解

/**
 * 一個簡單的模擬搜索包下面所有註解的工具類
 */
public class SearchAnnationsInPackage {

  public static void main(String[] args) {

    // 包下面的類
    Set<Class<?>> clazzs = getClasses("designPattern");
    if (clazzs == null) {
      return;
    }

    System.out.println( "class總量:" + clazzs.size());
    // 某類或者接口的子類
    //Set<Class<?>> inInterface = getByInterface(Object.class, clazzs);
    //System.out.printf(inInterface.size() + "");

    for (Class<?> clazz : clazzs) {

      // 獲取類上的註解
      Annotation[] annos = clazz.getAnnotations();
      for (Annotation anno : annos) {
        System.out.println(clazz.getSimpleName().concat(".").concat(anno.annotationType().getSimpleName()));
      }

      // 獲取方法上的註解
      Method[] methods = clazz.getDeclaredMethods();
      for (Method method : methods) {
        Annotation[] annotations = method.getDeclaredAnnotations();
        for (Annotation annotation : annotations) {
          System.out.println(clazz.getSimpleName().concat(".").concat(method.getName()).concat(".")
              .concat(annotation.annotationType().getSimpleName()));
        }
      }
    }
  }

  /**
   * 從包package中獲取所有的Class
   *
   * @param pack
   * @return
   */
  public static Set<Class<?>> getClasses(String pack) {

    // 第一個class類的集合
    Set<Class<?>> classes = new LinkedHashSet<>();
    // 是否循環迭代
    boolean recursive = true;
    // 獲取包的名字 並進行替換
    String packageName = pack;
    String packageDirName = packageName.replace('.', '/');
    // 定義一個枚舉的集合 並進行循環來處理這個目錄下的things
    Enumeration<URL> dirs;
    try {
      dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);
      // 循環迭代下去
      while (dirs.hasMoreElements()) {
        // 獲取下一個元素
        URL url = dirs.nextElement();
        // 得到協議的名稱
        String protocol = url.getProtocol();
        // 如果是以文件的形式保存在服務器上
        if ("file".equals(protocol)) {
          System.err.println("file類型的掃描");
          // 獲取包的物理路徑
          String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
          // 以文件的方式掃描整個包下的文件 並添加到集合中
          findAndAddClassesInPackageByFile(packageName, filePath, recursive, classes);
        } else if ("jar".equals(protocol)) {
          // 如果是jar包文件
          // 定義一個JarFile
          // System.err.println("jar類型的掃描");
          JarFile jar;
          try {
            // 獲取jar
            jar = ((JarURLConnection) url.openConnection()).getJarFile();
            // 從此jar包 得到一個枚舉類
            Enumeration<JarEntry> entries = jar.entries();
            // 同樣的進行循環迭代
            while (entries.hasMoreElements()) {
              // 獲取jar裏的一個實體 可以是目錄 和一些jar包裏的其他文件 如META-INF等文件
              JarEntry entry = entries.nextElement();
              String name = entry.getName();
              // 如果是以/開頭的
              if (name.charAt(0) == '/') {
                // 獲取後面的字符串
                name = name.substring(1);
              }
              // 如果前半部分和定義的包名相同
              if (name.startsWith(packageDirName)) {
                int idx = name.lastIndexOf('/');
                // 如果以"/"結尾 是一個包
                if (idx != -1) {
                  // 獲取包名 把"/"替換成"."
                  packageName = name.substring(0, idx).replace('/', '.');
                }
                // 如果可以迭代下去 並且是一個包
                if ((idx != -1) || recursive) {
                  // 如果是一個.class文件 而且不是目錄
                  if (name.endsWith(".class") && !entry.isDirectory()) {
                    // 去掉後面的".class" 獲取真正的類名
                    String className = name.substring(packageName.length() + 1, name.length() - 6);
                    try {
                      // 添加到classes
                      classes.add(Class.forName(packageName + '.' + className));
                    } catch (ClassNotFoundException e) {
                      e.printStackTrace();
                    }
                  }
                }
              }
            }
          } catch (IOException e) {
            // log.error("在掃描用戶定義視圖時從jar包獲取文件出錯");
            e.printStackTrace();
          }
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

    return classes;
  }

  /**
   * 以文件的形式來獲取包下的所有Class
   *
   * @param packageName
   * @param packagePath
   * @param recursive
   * @param classes
   */
  public static void findAndAddClassesInPackageByFile(String packageName, String packagePath, final boolean recursive,
                                                      Set<Class<?>> classes) {
    // 獲取此包的目錄 建立一個File
    File dir = new File(packagePath);
    // 如果不存在或者 也不是目錄就直接返回
    if (!dir.exists() || !dir.isDirectory()) {
      // log.warn("用戶定義包名 " + packageName + " 下沒有任何文件");
      return;
    }
    // 如果存在 就獲取包下的所有文件 包括目錄
    File[] dirfiles = dir.listFiles(new FileFilter() {
      // 自定義過濾規則 如果可以循環(包含子目錄) 或則是以.class結尾的文件(編譯好的java類文件)
      public boolean accept(File file) {
        return (recursive && file.isDirectory()) || (file.getName().endsWith(".class"));
      }
    });
    // 循環所有文件
    for (File file : dirfiles) {
      // 如果是目錄 則繼續掃描
      if (file.isDirectory()) {
        findAndAddClassesInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive,
            classes);
      } else {
        // 如果是java類文件 去掉後面的.class 只留下類名
        String className = file.getName().substring(0, file.getName().length() - 6);
        try {
          // 添加到集合中去
          // classes.add(Class.forName(packageName + '.' + className));
          // 經過回覆同學的提醒,這裏用forName有一些不好,會觸發static方法,沒有使用classLoader的load乾淨
          classes.add(
              Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));
        } catch (ClassNotFoundException e) {
          // log.error("添加用戶自定義視圖類錯誤 找不到此類的.class文件");
          e.printStackTrace();
        }
      }
    }
  }

  @SuppressWarnings({"rawtypes", "unchecked"})
  public static Set<Class<?>> getByInterface(Class clazz, Set<Class<?>> classesAll) {
    Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
    // 獲取指定接口的實現類
    if (!clazz.isInterface()) {
      try {
        /**
         * 循環判斷路徑下的所有類是否繼承了指定類 並且排除父類自己
         */
        Iterator<Class<?>> iterator = classesAll.iterator();
        while (iterator.hasNext()) {
          Class<?> cls = iterator.next();
          /**
           * isAssignableFrom該方法的解析,請參考博客:
           * http://blog.csdn.net/u010156024/article/details/44875195
           */
          if (clazz.isAssignableFrom(cls)) {
            if (!clazz.equals(cls)) {// 自身並不加進去
              classes.add(cls);
            } else {

            }
          }
        }
      } catch (Exception e) {
        System.out.println("出現異常");
      }
    }
    return classes;
  }
}

4. 註解的作用

Annotation 是一個輔助類,它在 Junit、Struts、Spring 等工具框架中被廣泛使用。

4.1 編譯檢查

Annotation 具有"讓編譯器進行編譯檢查的作用"。例如,@SuppressWarnings, @Deprecated 和 @Override 都具有編譯檢查作用。

4.2 在反射中使用 Annotation

在reflect庫中的的Class, Method, Field 等類都實現了AnnotatedElement接口,這也意味着,我們可以在反射中解析並使用 Annotation,詳細是使用方法可以參考第三節中的內容。

4.3 根據 Annotation 生成幫助文檔

通過給 Annotation 註解加上 @Documented 標籤,能使該 Annotation 標籤出現在 javadoc 中。

5. Spring中的註解編程模型

請至傳送門看我的另一篇設計模式相關的總結

6. 參考

https://www.runoob.com/w3cnote/java-annotation.html
https://www.jianshu.com/p/28edf5352b63
https://www.cnblogs.com/rinack/p/7606285.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章