获取类的步骤上的所有方法上的注解(二)
获取类的方法上的所有方法上的注解(二)
Student.java使用注解的类。可以看到这里直接在注解上加上了@Anno("Student get the age!")形式,如果Anno注解的属性并不是value,则需要写成:
打印:
接着上面的例子,实现获取具体注解的值
Anno.java注解的实现类,这里加入了属性value,便于在使用的Anno注解的时候可以,如此使用@Anno("coding"),这里还设置了注解的默认值。
其实也可以设置其他的属性。
package com.robot.test; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Anno { public String value() default "hello"; }
Student.java使用注解的类。可以看到这里直接在注解上加上了@Anno("Student get the age!")形式,如果Anno注解的属性并不是value,则需要写成:
@Anno(attr="Student get the age!")类似的形式,具体请参考相关注解的详细内容。
package com.robot.test; public class Student { public int age; public String name; @Anno("Student get the age!") public int getAge() { return age; } @Anno("Student set the age!") public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package com.robot.test; import java.lang.annotation.Annotation; import java.lang.reflect.Method; public class AnnotationTest { public static void main(String[] args) { Method[] methods = Student.class.getMethods(); for (Method method : methods) { Annotation[] annotations = method.getAnnotations(); for (Annotation annotation : annotations) { // 获取注解的具体类型 Class<? extends Annotation> annotationType = annotation.annotationType(); if (Anno.class == annotationType) { // 方式一:获取注解的具体的值 // Anno an = (Anno)annotation; // System.out.println(an.value()); // 方式二:获取注解的具体的值 Anno anno = (Anno) annotationType.cast(annotation); System.out.println(anno.value()); System.out.println(method.getName()+"()\t" + Anno.class.getName()); // 打印出java.lang.annotation.Annotation,注解类其实都实现了Annotation这个接口 Class<?>[] interfaces = Anno.class.getInterfaces(); System.out.println(interfaces[0].getName()); } } } } }
打印:
Student get the age! getAge() com.robot.test.Anno java.lang.annotation.Annotation Student set the age! setAge() com.robot.test.Anno java.lang.annotation.Annotation
具体详细的内容可以参考这篇博客:
http://www.cnblogs.com/peida/archive/2013/04/24/3036689.html
版权声明:本文为博主原创文章,未经博主允许不得转载。