在Java使用反射处理注解

我们使用注解的主要原因是因为它们是元数据。
所以这意味着我们应该能够在需要时获取这些元数据以利用注解信息。

在 java 中,我们必须使用反射 API 来访问任何类型(即类或者接口)或者方法上的注解。

示例:

package test.core.annotations;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
public class ProcessAnnotationExample
{
   public static void main(String[] args) throws NoSuchMethodException, SecurityException
   {
      new DemoClass();
      Class<DemoClass> demoClassObj = DemoClass.class;
      readAnnotationOn(demoClassObj);
      Method method = demoClassObj.getMethod("getString", new Class[]{});
      readAnnotationOn(method);
   }
   static void readAnnotationOn(AnnotatedElement element)
   {
      try
      {
         System.out.println("\n Finding annotations on " + element.getClass().getName());
         Annotation[] annotations = element.getAnnotations();
         for (Annotation annotation : annotations)
         {
            if (annotation instanceof JavaFileInfo)
            {
               JavaFileInfo fileInfo = (JavaFileInfo) annotation;
               System.out.println("Author :" + fileInfo.author());
               System.out.println("Version :" + fileInfo.version());
            }
         }
      } catch (Exception e)
      {
         e.printStackTrace();
      }
   }
}

输出:

Finding annotations on java.lang.Class
Author :unknown
Version :0.0
Finding annotations on java.lang.reflect.Method
Author :jackli
Version :1.0
日期:2020-09-17 00:09:59 来源:oir作者:oir