天天看点

Java注解(Annotation)自定义

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

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

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

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

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

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

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

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

Java代码

  1. package Test_annotation;   
  2. import java.lang.annotation.Documented;   
  3. import java.lang.annotation.Inherited;   
  4. import java.lang.annotation.Retention;   
  5. import java.lang.annotation.Target;   
  6. import java.lang.annotation.ElementType;   
  7. import java.lang.annotation.RetentionPolicy;   
  8. @Target(ElementType.METHOD)   
  9. @Retention(RetentionPolicy.RUNTIME)   
  10. @Documented  
  11. @Inherited  
  12. public @interface Test {   
  13.     public int id();   
  14.     public String description() default "no description";   
  15. }  
  16. 下面是一个使用注解 和 解析注解的实例

    Java代码

    1. package Test_annotation;   
    2. import java.lang.reflect.Method;   
    3. public class Test_1 {   
    4.     @Test(id = 1, description = "hello method_1")   
    5.     public void method_1() {   
    6.      }   
    7.     @Test(id = 2)   
    8.     public void method_2() {   
    9.      }   
    10.     @Test(id = 3, description = "last method")   
    11.     public void method_3() {   
    12.      }   
    13.     public static void main(String[] args) {   
    14.          Method[] methods = Test_1.class.getDeclaredMethods();   
    15.         for (Method method : methods) {   
    16.             boolean hasAnnotation = method.isAnnotationPresent(Test.class);   
    17.             if (hasAnnotation) {   
    18.                  Test annotation = method.getAnnotation(Test.class);   
    19.                  System.out.println("Test( method = " + method.getName()   
    20.                          + " , id = " + annotation.id() + " , description = "  
    21.                          + annotation.description() + " )");   
    22.              }   
    23.          }   
    24.      }   
    25. }