首先定义三个注解类, 分别适用于类,成员变量, 方法
- @Target(ElementType.TYPE)
- @Retention(RetentionPolicy.RUNTIME)
- public @interface LeiMode {
- public int value() default 1;
- }
- @Target(ElementType.FIELD)
- @Retention(RetentionPolicy.RUNTIME)
- public @interface FiledMode {
- public int value() default 1;
- }
- @Target(ElementType.METHOD)
- @Retention(RetentionPolicy.RUNTIME)
- public @interface TreahMode {
- public int value() default 1;
- }
然后,定义一个类,使用了注解
- @LeiMode(5)
- public class AnnotationDemo {
- @FiledMode(10)
- private int itest;
- @TreahMode()
- private void test(){}
- }
1.获取类上的注解值
- LeiMode annotation = AnnotationDemo.class.getAnnotation(LeiMode.class);
- System.out.println(annotation.value());
2.获取所有变量,并获取指定方法上的注解信息
- Field[] fields = AnnotationDemo.class.getDeclaredFields();
- Field field = null;
- for(Field f : fields){
- if(f.getName().equals("itest")){
- field = f;
- break;
- }
- }
- FiledMode annotation = field.getAnnotation(FiledMode.class);
- System.out.println(annotation.value());
3.获取指定变量上的注解信息
- Field field = AnnotationDemo.class.getDeclaredField("itest");
- FiledMode annotation = field.getAnnotation(FiledMode.class);
- System.out.println(annotation.value());
4.获取所有方法,并获取指定方法上的注解信息
- Method[] methods = AnnotationDemo.class.getDeclaredMethods(); //可以获取私有方法和公有方法, getMethods() 获取公有方法
- Method meth = null;
- for(Method method : methods){
- if(method.getName().equals("test")){
- meth = method;
- break;
- }
- }
- Annotation annotation = meth.getAnnotations()[0];
- TreahMode mode = (TreahMode) annotation;
- System.out.println(mode.value());
5.获取指定方法上的注解信息
- Method method = AnnotationDemo.class.getDeclaredMethod("test", null);//可以获取私有方法和公有方法
- System.out.println(method);
- Annotation[] annotations = method.getAnnotations();
- Annotation annotation = annotations[0];
- System.out.println(annotation);
- TreahMode mode = (TreahMode) annotation;
- System.out.println(mode.value());