java.lang.annotation包Annotation的基本原則:Annotation不能影響程序代碼的執行,無論增加、刪除Annotation,代碼都始終如一的執行元注解:負責注解其他的注解@Documented@Inherited@Retention@Target-------------------------------------------------------------------------------@Target用于描述Annotatiion的范圍取值有:java.lang.annotation.ElementTypeTYPE:類,接口(包括注解),枚舉FIELD:域(包括枚舉常量)METHOD:方法PARAMETER:參數CONSTRUCTOR:構造方法LOCAL_VARIABLE:局部變量ANNOTATION_TYPE:注解類型PACKAGE:包例子:
@Target(ElementType.TYPE)public String className();public @interface TargetTest {}*******************************************************************************@Retention用于描述Annotation的生命周期取值有:java.lang.annotation.RetentionPolicySOURCE:源文件有效CLASS:在Class文件中有效RUNTIME:在運行時有效,可通過反射獲取內容例子:
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)public @interface AnnonitionTargetTest {}*******************************************************************************@Documented用于描述Annotation被JavaDoc例子:
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@@Documented 則public @interface AnnonitionTargetTest {}生成javaDoc后調用@AnnonitionTargetTest 的類、方法等會出現@AnnonitionTargetTest,如果沒有@Documented 則調用@AnnonitionTargetTest 的類、方法等不會出現@AnnonitionTargetTest*******************************************************************************@Inherited用于描述Annotation可以被繼承如果一個使用了@Inherited修飾的annotation類型被用于一個class,則這個annotation將被用于該class的子類。注意:@Inherited annotation類型是被標注過的class的子類所繼承。不從接口繼承annotation,方法并不從重載的方法繼承annotation例子:
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Inheritedpublic @interface AnnonitionTargetTest {}*******************************************************************************自定義注解格式:public @interface 注解名{定義體}注解參數的可支持數據類型:1.所有基本數據類型2.String類型3.Class類型4.enum類型5.Annotation類型6.以上所有類型的數組訪問修飾符只有public 和default如果只有一個參數成員,最好把參數名稱設為"value",后加小括號*******************************************************************************注解處理器類:java.lang.reflect.AnnotatedElement它的實現類:java.lang.Class類,java.lang.reflect.Filed類,java.lang.reflect.Constructor類,java.lang.reflect.Method類,java.lang.Package類<T extends Annotation> T getAnnotation(Class<T> annotationClass); 返回改程序元素上存在的、指定類型的注解,如果該類型注解不存在,則返回null。Annotation[] getAnnotations();返回該程序元素上存在的所有注解。boolean isAnnotationPResent(Class<? extends Annotation> annotationClass);判斷該程序元素上是否包含指定類型的注解,存在則返回true,否則返回false.Annotation[] getDeclaredAnnotations();返回直接存在于此元素上的所有注釋。與此接口中的其他方法不同,該方法將忽略繼承的注釋。(如果沒有注釋直接存在于此元素上,則返回長度為零的一個數組。)該方法的調用者可以隨意修改返回的數組;這不會對其他調用者返回的數組產生任何影響。*******************************************************************************
圖片來源于網絡

新聞熱點
疑難解答