java 类,变量,方法上注解值的获取 | 您所在的位置:网站首页 › 获取注解的属性值是什么 › java 类,变量,方法上注解值的获取 |
首先定义三个注解类, 分别适用于类,成员变量, 方法 [java] view plain copy @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface LeiMode { public int value() default 1; } [java] view plain copy @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface FiledMode { public int value() default 1; } [java] view plain copy @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface TreahMode { public int value() default 1; } 然后,定义一个类,使用了注解 [java] view plain copy @LeiMode(5) public class AnnotationDemo { @FiledMode(10) private int itest; @TreahMode() private void test(){} }1.获取类上的注解值 [java] view plain copy LeiMode annotation = AnnotationDemo.class.getAnnotation(LeiMode.class); System.out.println(annotation.value());2.获取所有变量,并获取指定方法上的注解信息 [html] view plain copy 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.获取指定变量上的注解信息 [java] view plain copy Field field = AnnotationDemo.class.getDeclaredField("itest"); FiledMode annotation = field.getAnnotation(FiledMode.class); System.out.println(annotation.value());4.获取所有方法,并获取指定方法上的注解信息 [java] view plain copy 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.获取指定方法上的注解信息 [java] view plain copy 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()); |
CopyRight 2018-2019 实验室设备网 版权所有 |