Java使用反射获取注解信息的简介说明
下文笔者讲述使用java反射获取注解信息的方法分享,如下所示:
例:注解的使用
注解简介说明
注解可以理解为java代码的一个注释,注解本身不起任何作用,它需要借助反射为类做一些扩展功能例:注解的使用
//TestClass上使用了注解@MyAnnotation @MyAnnotation(name="java",value="java265.com") public class TestClass { } //定义注解 @Retention(RetentionPolicy.Runtime) @Target(ElementType.TYPE) public @interface MyAnnotation { public String name(); public String value(); }java访问注解的示例分享
Class aClass = TestClass.class; Annotation[] annotations = aClass.getAnnotations(); for(Annotation annotation : annotations){ if(annotation instanceof MyAnnotation){ MyAnnotation myAnnotation = (MyAnnotation) annotation; System.out.println("name: " + myAnnotation.name()); System.out.println("value: " + myAnnotation.value()); } }
方法注解
public class TestClass { @MyAnnotation(name="methoName", value = "this is method") public void testFun(){} } Method method = ... //获取方法对象 Annotation[] annotations = method.getDeclaredAnnotations(); for(Annotation annotation : annotations){ if(annotation instanceof MyAnnotation){ MyAnnotation myAnnotation = (MyAnnotation) annotation; System.out.println("name: " + myAnnotation.name()); System.out.println("value: " + myAnnotation.value()); } }
参数注解
public class TestClass { public static void testFun( @MyAnnotation(name="aName", value="aValue") String parameter){ } } //使用Method对象来访问方法参数注解 Method method = ... //获取方法对象 Annotation[][] parameterAnnotations = method.getParameterAnnotations(); Class[] parameterTypes = method.getParameterTypes(); int i=0; for(Annotation[] annotations : parameterAnnotations){ Class parameterType = parameterTypes[i++]; for(Annotation annotation : annotations){ if(annotation instanceof MyAnnotation){ MyAnnotation myAnnotation = (MyAnnotation) annotation; System.out.println("param: " + parameterType.getName()); System.out.println("name : " + myAnnotation.name()); System.out.println("value: " + myAnnotation.value()); } } } --------------------- 注意事项: Method.getParameterAnnotations()方法返回一个注解类型的二维数组
变量注解
public class TestClass { @MyAnnotation(name="someName", value = "Hello World") public String myField = null; } Field field = ... //获取方法对象 Annotation[] annotations = field.getDeclaredAnnotations(); for(Annotation annotation : annotations){ if(annotation instanceof MyAnnotation){ MyAnnotation myAnnotation = (MyAnnotation) annotation; System.out.println("name: " + myAnnotation.name()); System.out.println("value: " + myAnnotation.value()); } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。