Java Annotation Examples

来源:互联网 发布:php购物车源码 编辑:程序博客网 时间:2024/05/16 02:02

Define Annotaion

import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ElementType.TYPE, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)public @interface JavaFileInfo {   String author() default "unknown";   String version() default "0.0";}

Use Annotation

@JavaFileInfopublic class DemoClass{   @JavaFileInfo(author = "Lokesh", version = "1.0")   public String getString()   {      return null;   }}

Processing Annotations Using Reflection

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

Execute Output

 Finding annotations on java.lang.ClassAuthor :unknownVersion :0.0 Finding annotations on java.lang.reflect.MethodAuthor :LokeshVersion :1.0

References

Complete Java Annotations Tutorial
Compile Time Validation using Java Annotation Processor
Lesson: Annotations

原创粉丝点击