如何使用java自定义注解?demo

1、Description.java 

  package kzfy.bk.com;   
    
  import java.lang.annotation.Documented;   
  import java.lang.annotation.ElementType;   
  import java.lang.annotation.Retention;   
  import java.lang.annotation.RetentionPolicy;   
  import java.lang.annotation.Target;   
    
  @Target(ElementType.TYPE)   
  @Retention(RetentionPolicy.RUNTIME)   
  @Documented  
  public @interface Description {   
      String value();   
  } 

 2、Name.java 

  package kzfy.bk.com;   
    
  import java.lang.annotation.Documented;   
  import java.lang.annotation.ElementType;   
  import java.lang.annotation.Retention;   
  import java.lang.annotation.RetentionPolicy;   
  import java.lang.annotation.Target;   
   
   //注意这里的@Target与@Description里的不同,参数成员也不同   
  @Target(ElementType.METHOD)   
  @Retention(RetentionPolicy.RUNTIME)   
  @Documented  
  public @interface Name {   
      String originate();   
      String community();   
  } 

3、MyTest.java 

  package kzfy.bk.com;   
    
  @Description("我的第一个使用自定义注解的类!")   
  public class MyTest{   
      @Name(originate="空中飞鱼",community="java")   
      public String getName(){   
          return "java,我的人生路!";
      }   
         
      @Name(originate="博客园",community="写博客")   
      public String getName2() {   
          return "博客,新的征程!";   
      }   
  } 

4、运行提取MyTest的类TestAnnotation.java

  package kzfy.bk.com;   
  
  import java.lang.reflect.Method;   
  import java.util.HashSet;   
  import java.util.Set;   
  
  public class TestAnnotation {   
      /**   
       * Annotation的API的用法请参见javaDoc文档  
       */  
       public static void main(String[] args) throws Exception {   
           String  CLASS_NAME ="kzfy.bk.com.MyTest";   
           Class  test = Class.forName(CLASS_NAME);   
           boolean flag = test.isAnnotationPresent(Description.class);   
            if(flag){   
                Description des = (Description)test.getAnnotation(Description.class);   
                System.out.println("描述:"+des.value());   
                System.out.println("-----------------");   
            }   
           
            //把JavaEyer这一类有利用到@Name的全部方法保存到Set中去   
            Method[] method = test.getMethods(); 
            Set<Method> set = new HashSet<Method>();   
            for(int i=0;i<method.length;i++) {   
                boolean otherFlag = method[i].isAnnotationPresent(Name.class);   
                if(otherFlag) set.add(method[i]);   
            }   
            for(Method m: set) {   
                Name name = m.getAnnotation(Name.class);   
                System.out.println("orginate:"+name.originate());   
                System.out.println("community:"+name.community());   
            }   
      }   
} 

 

posted @ 2016-02-25 10:59  云中飞鱼  阅读(1670)  评论(0编辑  收藏  举报