筆記來源: IMOOC Java註解
按照運行機制分java
.class
文件就不存在了.class
文件中都存在按照來源分函數
@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
爲成員指定一個默認值String
、Class
、Annotation
、Enumeration
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(); }
註解的做用範圍 @Target
和生命週期 @Retention
ip