获取类的方法上的所有方法上的注解(二)

来源:互联网 发布:淘宝网天猫刷单好评 编辑:程序博客网 时间:2024/05/22 04:24

接着上面的例子,实现获取具体注解的值


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;}}


AnnotationTest.java测试类:


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.Annojava.lang.annotation.AnnotationStudent set the age!setAge()com.robot.test.Annojava.lang.annotation.Annotation


从上图可以看出这里就获取了Student的方法上注解的具体的值了,实际项目中可以根据具体的值进行相关的操作。


具体详细的内容可以参考这篇博客:

http://www.cnblogs.com/peida/archive/2013/04/24/3036689.html

0 0
原创粉丝点击