Java用@interface Annotation{} 定一个注解@Annotion,一个注解是一个类。

@Override,@Deprecated,@SuppressWarnings为常见的3个注解。
注解相当于一种标记,在程序中加上了注解就等于为程序加上了某种标记,以后,
JAVAC编译器,开发工具和其他程序可以用反射来了解你的类以及各种元素上有无任何标记,看你有什么标记,就去干相应的事

注解@Override用在方法上,当我们想重写一个方法时,在方法上加@Override,当我们方法的名字出错时,编译器就会报错,如图:


       注解@Deprecated,用来表示某个类的属性或方法已经过时,不想别人再用时,在属性和方法
上用@Deprecated修饰,如图:

  注解@SuppressWarnings用来压制程序中出来的警告,比如在没有用泛型或是方法已经过时的时候,
 如图:

  

定一个注解:

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation
{
 String hello() default "gege";
  String world();
  int[] array() default { 2, 4, 5, 6 };
  EnumTest.TrafficLamp lamp() ;
  TestAnnotation lannotation() default @TestAnnotation(value = "ddd");
  Class style() default String.class;
}

上面程序中,定义一个注解@MyAnnotation,定义了6个属性,他们的名字为:  

hello,world,array,lamp,lannotation,style.  

  • 属性hello类型为String,默认值为gege  
  • 属性world类型为String,没有默认值  
  • 属性array类型为数组,默认值为2,4,5,6  
  • 属性lamp类型为一个枚举,没有默认值  
  • 属性lannotation类型为注解,默认值为@TestAnnotation,注解里的属性是注解  
  • 属性style类型为Class,默认值为String类型的Class类型 
  • 看下面例子:定义了一个MyTest类,用注解@MyAnnotation修饰,注解@MyAnnotation定义的属性都赋了值
  • @MyAnnotation(hello = "beijing", world="shanghai",array={},lamp=TrafficLamp.RED,style=int.class)
    public class MyTest
    {
     @MyAnnotation(lannotation=@TestAnnotation(value="baby"), world = "shanghai",array={1,2,3},lamp=TrafficLamp.YELLOW)
     @Deprecated
     @SuppressWarnings("")
     public void output()
     {
      System.out.println("output something!");
     }
    }

    接着通过反射读取注解的信息:  

  • public class MyReflection
    {
     public static void main(String[] args) throws Exception
     {
      MyTest myTest = new MyTest();
        Class<MyTest> c = MyTest.class;
        Method method = c.getMethod("output", new Class[] {});
           //如果MyTest类名上有注解@MyAnnotation修饰,则为true  
      if(MyTest.class.isAnnotationPresent(MyAnnotation.class))
      {
       System.out.println("have annotation");
      }
       if (method.isAnnotationPresent(MyAnnotation.class))
       {
       method.invoke(myTest, null); //调用output方法
       //获取方法上注解@MyAnnotation的信息  
         MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
        String hello = myAnnotation.hello();
       String world = myAnnotation.world();
       System.out.println(hello + ", " + world);//打印属性hello和world的值  
       System.out.println(myAnnotation.array().length);//打印属性array数组的长度  
       System.out.println(myAnnotation.lannotation().value()); //打印属性lannotation的值  
       System.out.println(myAnnotation.style());
       }
        //得到output方法上的所有注解,当然是被RetentionPolicy.RUNTIME修饰的  
         Annotation[] annotations = method.getAnnotations();
          for (Annotation annotation : annotations)
      {
       System.out.println(annotation.annotationType().getName());
      }
       }
    }

    代码打印:

  • have annotation
    output something!
    gege, shanghai
    
    baby
    class java.lang.String
    com.heima.annotation.MyAnnotation
    java.lang.Deprecated
02-13 18:39