【Java註解】註解基礎

筆記來源: IMOOC Java註解

註解的分類

  • 按照運行機制分java

    • 源碼註解:註解只在源碼中存在,編譯成 .class 文件就不存在了
    • 編譯時註解:註解在源碼和 .class 文件中都存在
    • 運行時註解:在運行階段還起做用,甚至會影響運行邏輯的註解
  • 按照來源分函數

    • 來自JDK的註解
    • 來自第三方的註解
    • 咱們本身定義的註解
  • 元註解:給註解進行註解

自定義註解

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Description { // 使用 @interface 關鍵字定義註解
    String desc(); // 成員以無參無異常方式聲明
    String author();
    int age() default 18; // 能夠用 default 爲成員指定一個默認值
}

自定義註解的語法要求

  • 使用 @interface 關鍵字定義註解
  • 成員以無參無異常方式聲明
  • 能夠用 default 爲成員指定一個默認值
  • 成員類型是受限的,合法的類型包括原始類型及 StringClassAnnotationEnumeration
  • 若是註解只有一個成員,則成員名必須取名爲 value(),在使用時能夠忽略成員名和賦值號 =
  • 註解類能夠沒有成員,沒有成員的註解稱爲標識註解

註解的註解(元註解)

  • @Target:註解的做用域code

    • 包、類、字段、方法、方法的參數、局部變量
  • @Retention:註解的生命週期繼承

    • SOURCE:只在源碼顯示,編譯時會丟棄
    • CLASS:編譯時會記錄到 class 中,運行時忽略
    • RUNTIME:運行時存在,能夠經過反射讀取
  • @Inherited:標識性註解,容許子類繼承(接口實現是沒有任何做用的,只會繼承類註解,不會繼承其餘如方法的註解)
  • @Document:生成 javadoc 時會包含註解

使用自定義註解

@Description(desc = "I am eyeColor", author = "Mooc boy", age = 18)
public String eyeColor() {
    return "red";
}

@<註解名>(<成員名1> = <成員值1>, <成員名2> = <成員值2>, ...)接口

解析註解

概念:經過反射獲取類、函數或成員上的運行時註解信息,從而實現動態控制程序運行的邏輯。生命週期

@Description(desc = "I am Example", author = "Mooc boy", age = 18)
public class Example {
    @Description(desc = "I am eyeColor", author = "Mooc boy", age = 18)
    public String eyeColor() {
        return "red";
    }
}
try {
    // 1. 使用類加載器加載類
    Class c - Class.forName("Example");
    // 2. 找到類上面的註解
    boolean isExist = c.isAnnotationPresent(Description.class);
    if (isExist) {
        // 3. 拿到註解實例
        Description d = (Description) c.getAnnotation(Description.class);
        System.out.println(d.desc());
    }
    Method[] ms = c.getMethods();
    // 4-1. 找到方法上的註解
    for (Method m: ms) {
        boolean isMExist = m.isAnnotationPresent(Description.class);
        if (isMExist) {
            Description d = (Description) c.getAnnotation(Description.class);
            System.out.println(d.desc());
        }
    }
    // 4-2. 找到方法上的註解
    for (Method m: ms) {
        Annotation[] as = m.getAnnotations();
        for (Annotation a: as) {
            Description d = (Description) a;
            System.out.println(d.desc());
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}

總結

  1. 認識註解
  2. 註解的做用範圍 @Target 和生命週期 @Retentionip

    • 做用範圍:包、類、字段、方法、方法的參數、局部變量
    • 生命週期:源文件、編譯時、運行時
  3. 能讀懂註解
  4. 能在實際項目中用註解解決問題,並能自定義註解
相關文章
相關標籤/搜索