Java元注解


元注解是指注解的注解,包括@Retention @Target @Document @Inherited四種。

1.@Retention: 定義注解的保留策略
@Retention(RetentionPolicy.SOURCE)   //注解僅存在於源碼中,在class字節碼文件中不包含
@Retention(RetentionPolicy.CLASS)     // 默認的保留策略,注解會在class字節碼文件中存在,但運行時無法獲得,
@Retention(RetentionPolicy.RUNTIME)  // 注解會在class字節碼文件中存在,在運行時可以通過反射獲取到
首 先要明確生命周期長度 SOURCE < CLASS < RUNTIME ,所以前者能作用的地方后者一定也能作用。一般如果需要在運行時去動態獲取注解信息,那只能用 RUNTIME 注解;如果要在編譯時進行一些預處理操作,比如生成一些輔助代碼(如 ButterKnife),就用 CLASS注解;如果只是做一些檢查性的操作,比如 @Override 和 @SuppressWarnings,則可選用 SOURCE 注解。


2.@Target:定義注解的作用目標
源碼為:
@Documented  
@Retention(RetentionPolicy.RUNTIME)  
@Target(ElementType.ANNOTATION_TYPE)  
public @interface Target {  
    ElementType[] value();  
}  
@Target(ElementType.TYPE)   //接口、類、枚舉、注解
@Target(ElementType.FIELD) //字段、枚舉的常量
@Target(ElementType.METHOD) //方法
@Target(ElementType.PARAMETER) //方法參數
@Target(ElementType.CONSTRUCTOR)  //構造函數
@Target(ElementType.LOCAL_VARIABLE)//局部變量
@Target(ElementType.ANNOTATION_TYPE)//注解
@Target(ElementType.PACKAGE) ///包    
3.@Document:說明該注解將被包含在javadoc中
4.@Inherited:說明子類可以繼承父類中的該注解
舉例:

// 適用類、接口(包括注解類型)或枚舉  
@Retention(RetentionPolicy.RUNTIME)  
@Target(ElementType.TYPE)  
public @interface ClassInfo {  
    String value();  
}  
    
// 適用field屬性,也包括enum常量  
@Retention(RetentionPolicy.RUNTIME)  
@Target(ElementType.FIELD)  
public @interface FieldInfo {  
    int[] value();  
}  
// 適用方法  
@Retention(RetentionPolicy.RUNTIME)  
@Target(ElementType.METHOD)  
public @interface MethodInfo {  
    String name() default "long";  
    String data();  
    int age() default 27;  
}  

這3個注解分別適用於不同的元素,並都帶有不同的屬性,在使用注解是需要設置這些屬性值。
再定義一個測試類來使用這些注解:

@ClassInfo("Test Class")  
public class TestRuntimeAnnotation {  
 
    @FieldInfo(value = {1, 2})  
    public String fieldInfo = "FiledInfo";  
 
    @FieldInfo(value = {10086})  
    public int i = 100;  
 
    @MethodInfo(name = "BlueBird", data = "Big")  
    public static String getMethodInfo() {  
        return TestRuntimeAnnotation.class.getSimpleName();  
    }  
}  
在代碼中獲取注解信息:
private void _testRuntimeAnnotation() {  
    StringBuffer sb = new StringBuffer();  
    Class<?> cls = TestRuntimeAnnotation.class;  
    Constructor<?>[] constructors = cls.getConstructors();  
    // 獲取指定類型的注解  
    sb.append("Class注解:").append("\n");  
    ClassInfo classInfo = cls.getAnnotation(ClassInfo.class);  
    if (classInfo != null) {  
        sb.append(Modifier.toString(cls.getModifiers())).append(" ")  
                .append(cls.getSimpleName()).append("\n");  
        sb.append("注解值: ").append(classInfo.value()).append("\n\n");  
    }  
 
    sb.append("Field注解:").append("\n");  
    Field[] fields = cls.getDeclaredFields();  
    for (Field field : fields) {  
        FieldInfo fieldInfo = field.getAnnotation(FieldInfo.class);  
        if (fieldInfo != null) {  
            sb.append(Modifier.toString(field.getModifiers())).append(" ")  
                    .append(field.getType().getSimpleName()).append(" ")  
                    .append(field.getName()).append("\n");  
            sb.append("注解值: ").append(Arrays.toString(fieldInfo.value())).append("\n\n");  
        }  
    }  
 
    sb.append("Method注解:").append("\n");  
    Method[] methods = cls.getDeclaredMethods();  
    for (Method method : methods) {  
        MethodInfo methodInfo = method.getAnnotation(MethodInfo.class);  
        if (methodInfo != null) {  
            sb.append(Modifier.toString(method.getModifiers())).append(" ")  
                    .append(method.getReturnType().getSimpleName()).append(" ")  
                    .append(method.getName()).append("\n");  
            sb.append("注解值: ").append("\n");  
            sb.append("name: ").append(methodInfo.name()).append("\n");  
            sb.append("data: ").append(methodInfo.data()).append("\n");  
            sb.append("age: ").append(methodInfo.age()).append("\n");  
        }  
    }  
 
    System.out.print(sb.toString());  
}  

 

 


免責聲明!

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



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