一個自定義注解由源注解和方法構成
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Myannotation {
String value() default "";
String name() default "";
}
1.方法
public String value() default "";
public String name() default "";
一般預設public可以不寫,string表示傳回值;default如果不寫,注解使用時一定要寫值;
注解的使用:
@Myannotation(key="");key指定是定義注解的方法名;如果方法名是value可以省略key
如:@Myannotation(“對應value的值”),@Myannotation(name=“對應name的值”)
2.源注解(規範注解的注解)
2.1 @target描述目前注解的作用範圍
@target(ElementType.ANNOTATION_TYPE)--目前注解隻能出現在注解上
ElementType.TYPE--類,接口(包括注解),枚舉
ElementType.FIELD--屬性上
ElementType.METHOD--方法
ElementType.PARAMETER--方法參數上
ElementType.CONSTRUCTOR
ElementType.LOCAL_VARIABLE--局部變量
ElementType.PACKAGE---包
jdk1.8新加入的特性:
ElementType.TYPE_PARAMETER---類參數上(一般用于規範泛型)
如:public class AnnotationTypeParameter<@TestTypeParam T> {}
ElementType.TYPE_USE --所有都可以
jdk1.9新加入的特性:
ElementType.MODULE--暫時不了解
如果注解上沒加@target表示目前注解适用于所有注解
2.2 @Retention 保留(目前注解的生命周期)預設是源碼中.java檔案中到.class檔案中就不保留
@Retention(RetentionPolicy.SOURCE)--預設在源碼中;到.class就丢失了注解
@Retention(RetentionPolicy.CLASS)---位元組碼中;到jvm運作時就丢失了注解
@Retention(RetentionPolicy.RUNTIME)--運作時
位元組碼時跟運作時的差別?
.java檔案--jdk編譯--.class檔案---放到jvm中運作(運作時)
3.運用注解(擷取注解資訊)
@Test
public void annotationTest(){
Class<MyConfig> clazz = MyConfig.class;
//判斷目前類上是否有@myannotation注解
Class<Myannotation> annotation = Myannotation.class;
if(clazz.isAnnotationPresent(annotation)){
Myannotation annotation1 = clazz.getAnnotation(annotation);
System.out.println(annotation1.value());
System.out.println(annotation1.name());
System.out.println(annotation1.shabi());
}
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if(method.isAnnotationPresent(annotation)){
Myannotation annotation2 = method.getAnnotation(annotation);
System.out.println(annotation2.value());
System.out.println(annotation2.name());
System.out.println(annotation2.shabi());
}
}