package annotion;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
@Father(mm = "类上")
public class Annotions {
@Father(mm = "变量上")
int a = 5;
@Father(mm = "方法上")
public static void main(@Father(mm = "方法参数上") String[] args) throws NoSuchMethodException, NoSuchFieldException {
Annotions annotions = new Annotions();
Class aClass = annotions.getClass();
//获取Father的注解
Father annotation = (Father) aClass.getAnnotation(Father.class);
System.out.println(annotation == null);
System.out.println(annotation.mm());
//获取方法上的的注解
Method main = aClass.getMethod("main", String[].class);
Annotation[] annotations = main.getDeclaredAnnotations();
for (Annotation item : annotations
) {
Father item1 = (Father) item;
System.out.println(item1.mm());
}
//获取方法参数上上的的注解
Annotation[][] annotations1 = main.getParameterAnnotations();
Father father = (Father) annotations1[0][0];
System.out.println(father.mm());
//获取变量上的的注解
Field a1 = aClass.getDeclaredField("a");
Father annotation1 = a1.getAnnotation(Father.class);
System.out.println(annotation1.mm());
}
}
package annotion;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Father {
@Son(msg = "儿子")
String mm() default "";
}