注解相当于一种标记,在程序中加了注解就等于为程序打上了某种标记,没加,则等于没有某种标记,以后,javac编译器,开发工具和其他程序可以用反射来了解你的类及各种元素上有无何种标记,看你有什么标记,就去干相应的事。标记可以加载包、类、字段、方法、方法的参数及局部变量上。
注解的三个阶段:java源文件-->Class文件-->内存中的字节码
默认值是在(defaults to RetentionPolicy.CLASS)Class阶段
@Override注解范围是在源文件、@SuppressWarnings注解的范围是在源代码、Retention注解范围在内存。
例子:
1、先定义自己的Annotation
- @Retention(RetentionPolicy.RUNTIME)
- @Target({ElementType.METHOD,ElementType.TYPE})
- public @interface MyAnnotation {
- //String color();//默认就是public的抽象方法
- String color() default "red";
- int[] array() default {1,2,3};
- String value();
- EnumTest.TrafficLamp lamp() default EnumTest.TrafficLamp.RED;
- MetaAnnotation annotation() default @MetaAnnotation("anntation");
- Class get() default String.class;
- }
2、在类中用自己的Annotation
- @MyAnnotation(value="123",array={3,4,5},annotation=@MetaAnnotation("yanshao"),get=Integer.class)
- public class AnnotationTest {
- public static void main(String[] args) throws Exception{
- if(AnnotationTest.class .isAnnotationPresent(MyAnnotation.class)){
- //MyAnnotation annotation = (MyAnnotation)MyAnnotation.class.newInstance();
- MyAnnotation annotation2 = (MyAnnotation)AnnotationTest.class
- .getAnnotation(MyAnnotation.class);
- //打印自定义的注释的一些属性。
- System.out.println(annotation2.color());
- System.out.println(annotation2.value());
- System.out.println(annotation2.array().length);
- System.out.println(annotation2.lamp());
- System.out.println(annotation2.annotation().value());
- System.out.println(annotation2.get());
- }
- }
- }