发新话题
移动帖子 加入精华 加入置顶 加入收藏 关注此帖

Java Annotation(4)



Java Annotation(4)

摘要
本文是该系列文章中的最后一篇文章,作为收尾,本文主要讲解如何通过Java反射来获得我们想要的注释信息,如果你对反射比较熟悉,那你应该能轻而易举的读取到想要的注释信息。



读取注释信息

当我们想读取某个注释信息时,我们是在运行时通过反射来实现的,如果你对元注释还有点印象,那你应该记得我们需要将保持性策略设置为RUNTIME,也就是说只有注释标记了@Retention(RetentionPolicy.RUNTIME)的,我们才能通过反射来获得相关信息,下面的例子我们将沿用前面几篇文章中出现的代码,并实现读取AnnotationTest类所有方法标记的注释并打印到控制台。好了,我们来看看是如何实现的吧:

package com.gelc.annotation.demo.reflect;
import java.lang.annotation.Annotation;=
import java.lang.reflect.Method;
public class AnnotationIntro {
  public static void main(String[] args) throws Exception {
    Method[] methods = Class.forName("com.gelc.annotation.demo.customize.AnnotationTest").getDeclaredMethods();
    Annotation[] annotations;
    for (Method method : methods) {
      annotations = method.getAnnotations();
      for (Annotation annotation : annotations) {
        System.out.println(method.getName() + " : " + annotation.annotationType().getName());
      }
    }
  }
}
快乐渡过每一天,减肥坚持每一天
编辑 回复 快速回复 TOP

Re:Java Annotation(4)

再一次看好想突然明白了好多东西
编辑 回复 快速回复 TOP
发新话题