annotation 自定义注解

来源:互联网 发布:谷歌地图软件 编辑:程序博客网 时间:2024/06/05 01:51



----------------------annotation----------------------------------------------------------------------


内建annotation的RetentionPolicy 基本使用


------自定义注解---必须在自己的文件夹呢
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;


@Retention(value=RetentionPolicy.RUNTIME) //表示此annotation在运行的时候有效
public  @interface Sty {
public String key() default "hahaha";
public String hello() default "xx";
        public String[] hello2() ; //定义一个数组
}


------使用自定义注解---------------------
@Sty(key = "999",hello="000",hello2={"111","2","ppp"})
public class TTTT {


}






-------通过反射取得annotation----------------
Class<?> class1 = Class.forName("com.dt.annotation.Demo");
Method method = class1.getMethod("toString");
Annotation annotation[] = method.getAnnotations();
for(Annotation annotation2:annotation){
System.out.println(annotation2);
}






-----------------------------
@Sty(key = "999",hello="000")
public class TTTT {


public static void main(String[] args) throws Exception {


Class<?> class1 = Class.forName("com.dt.annotation.Demo");
Method method = class1.getMethod("toString");
Annotation annotation[] = method.getAnnotations();
for(Annotation annotation2:annotation){
System.out.println(annotation2);
}


if (method.isAnnotationPresent(Sty.class)) {
Sty aSty = method.getAnnotation(Sty.class);  //Sty.class 是自定义annotation
String key = aSty.key();
String hello=aSty.hello();
System.out.println(key+" ,"+hello);
}


}


}