import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD,ElementType.LOCAL_VARIABLE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationTest {
//定义两个成员变量
String name() default "JACK";
int age() default 20;
}
package com.betasoft;
import java.lang.annotation.Annotation;
public class TestAnnotation {
public static void main(String[] args) {
try {
TestAnnotation t = new TestAnnotation();
t.getInfo();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
}
}
@AnnotationTest(name="张三",age=26)
public void getInfo() throws NoSuchMethodException, SecurityException{
//获取TestAnnotation对象getinfo方法里的所有注解
Annotation[] annos = TestAnnotation.class.getMethod("getInfo").getAnnotations();
//遍历annos数组
for(Annotation ann: annos){
//ann就是一个Annotation对象
//判断当前ann是否是AnnotationTest类型
if(ann instanceof AnnotationTest){
System.out.println("ann是"+ann);
//需要将ann强制转成AnnotationTest
System.out.println("ann的name是"+((AnnotationTest)ann).name());
System.out.println("ann的age是"+((AnnotationTest)ann).age());
}
}
}
}