---
title: "JAVA注解 "
author: "netli"
date: "2011-09-06T16:37:14Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2011-09-06T16:37:14Z"
id: 1166804
url: "https://netli.iteye.com/blog/1166804"
---

注解（Annotation） 为我们在代码中天界信息提供了一种形式化的方法，是我们可以在稍后

某个时刻方便地使用这些数据（通过 解析注解 来使用这些数据）。

 

    注解的语法比较简单，除了@符号的使用以外，它基本上与java的固有语法一致，java内置了三种

注解，定义在java.lang包中。

      **@Override**  表示当前方法是覆盖父类的方法。

      **@Deprecated**  表示当前元素是不赞成使用的。

      **@SuppressWarnings** 表示关闭一些不当的编译器警告信息。

 

  下面是一个定义注解的实例

package Test\_annotation;

import java.lang.annotation.Documented;  
import java.lang.annotation.Inherited;  
import java.lang.annotation.Retention;  
import java.lang.annotation.Target;  
import java.lang.annotation.ElementType;  
import java.lang.annotation.RetentionPolicy;

/*  
\* 元注解@Target,@Retention,@Documented,@Inherited  
*      
*         @Target 表示该注解用于什么地方，可能的 ElemenetType 参数包括：  
*                 ElemenetType.CONSTRUCTOR 构造器声明  
*                 ElemenetType.FIELD 域声明（包括 enum 实例）  
*                 ElemenetType.LOCAL\_VARIABLE 局部变量声明  
*                 ElemenetType.METHOD 方法声明  
*                 ElemenetType.PACKAGE 包声明  
*                 ElemenetType.PARAMETER 参数声明  
*                 ElemenetType.TYPE 类，接口（包括注解类型）或enum声明  
*                      
*         @Retention 表示在什么级别保存该注解信息。可选的 RetentionPolicy 参数包括：  
*                 RetentionPolicy.SOURCE 注解将被编译器丢弃  
*                 RetentionPolicy.CLASS 注解在class文件中可用，但会被VM丢弃  
*                 RetentionPolicy.RUNTIME VM将在运行期也保留注释，因此可以通过反射机制读取注解的信息。  
*                      
*         @Documented 将此注解包含在 javadoc 中  
*              
*         @Inherited 允许子类继承父类中的注解  
*          
\*/  
@Target(ElementType.METHOD)  
@Retention(RetentionPolicy.RUNTIME)  
@Documented  
@Inherited  
/*  
\* 定义注解 Test  
\* 注解中含有两个元素 id 和 description  
\* description 元素 有默认值 "no description"  
\*/  
public @interface Test {  
  public int id();  
  public String description() default "no description";  
}

 

下面是一个使用注解 和 解析注解的实例

package Test\_annotation;

import java.lang.reflect.Method;

public class Test\_1 {  
  /*  
    * 被注解的三个方法  
    \*/  
  @Test(id = 1, description = "hello method\_1")  
  public void method\_1() {  
  }

  @Test(id = 2)  
  public void method\_2() {  
  }

  @Test(id = 3, description = "last method")  
  public void method\_3() {  
  }

  /*  
    * 解析注解，将Test\_1类 所有被注解方法 的信息打印出来  
    \*/  
  public static void main(String\[] args) {  
    Method\[] methods = Test\_1.class.getDeclaredMethods();  
    for (Method method : methods) {  
      /*  
        * 判断方法中是否有指定注解类型的注解  
        \*/  
      boolean hasAnnotation = method.isAnnotationPresent(Test.class);  
      if (hasAnnotation) {  
        /*  
         * 根据注解类型返回方法的指定类型注解  
         \*/  
        Test annotation = method.getAnnotation(Test.class);  
        System.out.println("Test( method = " + method.getName()  
            + " , id = " + annotation.id() + " , description = "  
            + annotation.description() + " )");  
      }  
    }  
  }

}

输出结果如下：

    Test( method = method\_1 , id = 1 , description = hello method\_1 )

    Test( method = method\_2 , id = 2 , description = no description )

    Test( method = method\_3 , id = 3 , description = last method )

 

实例二：

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

package test1;  
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.METHOD)  
@Retention(RetentionPolicy.RUNTIME)  
@Documented  
public @interface Name {  
String originate();  
String community();  
}  
      
package test1;  
@Description("javaeye")  
public class JavaEyer {  
@Name(originate="1:robbin",community="javaEye")  
public String getName(){  
    return null;  
}  
@Name(originate="2:3",community="springside")  
public String getName2()  
{  
    return "4!";  
}  
}  
    

package test1;  
import java.lang.reflect.Method;  
import java.util.HashSet;  
import java.util.Set;  
public class TestAnnotation {  
public static void main(String\[] args) throws Exception {  
    String CLASS\_NAME = "test1.JavaEyer";  
    Class test = Class.forName(CLASS\_NAME);  
    Method\[] method = test.getMethods();  
    boolean flag = test.isAnnotationPresent(Description.class);  
    if(flag)  
    {  
     Description des = (Description)test.getAnnotation(Description.class);  
     System.out.println("bb:"+des.value());  
     System.out.println("-----------------");  
    }  
    Set&lt;Method&gt; set = new HashSet&lt;Method&gt;();  
    for(int i=0;i&lt;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(name.originate());  
     System.out.println("aaa:"+name.community());  
    }  
}  
}