注解相当于一种标记,在程序中加了注解就等于为程序打上了某种标记,没加,则等于没有某种标记,以后,javac编译器,开发工具和其他程序可以用反射来了解你的类及各种元素上有无何种标记,看你有什么标记,就去干相应的事。标记可以加在包,类,字段,方法,方法的参数以及局部变量上。
看java.lang包,可看到JDK中提供的最基本的annotation。
@SuppressWarnings //消除警告
@Deprecated //不建议使用 、过时的
@Override //方法的重写 注意public boolean equals(Objet other) 如果参数不是Object类型的,这是方法的重载!别大意。
注解就相当于一个你的源程序中要调用的一个类,要在源程序中应用某个注解,得先准备好了这个注解类。就像你要调用某个类,得先有开发好这个类。
1.定义一个最简单的注解:public @interface MyAnnotation {}
[RetetionPolicy.SOURCE、RetetionPolicy.SOURCE、RetetionPolicy.RUNTIME]
3.@Target元注解
Target的默认值为任何元素,设置Target等于ElementType.METHOD,原来加在类上的注解就报错了,改为用数组方式设置{ElementType.METHOD,ElementType.TYPE}就可以了。
元注解以及其枚举属性值不用记,只要会看jdk提供那几个基本注解的API帮助文档的定义或其源代码,按图索骥即可查到,或者直接看java.lang.annotation包下面的类。
public @interface MetaAnnotation//这是一个注解类 { String nextDay(); }
import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) //保留到运行时--》这是元注解,注解的注解 @Target({ElementType.METHOD,ElementType.TYPE})//可以查阅帮助文档-->ElementType public @interface MyAnnotation//这是一个注解类 { String color() default "bule";//默认是 public abstract String value(); int[] arrayAttr() default {1,2,3};//数组属性的注解类型 Class getCls() default String.class;//字节码属性的注解类型 EnumTest.TrafficLamp lamp() default EnumTest.TrafficLamp.GREEN;//枚举属性的注解类型 MetaAnnotation annotationAttr() default @MetaAnnotation(nextDay="1月1号");//注解属性的注解类型 }
import java.util.Arrays; @MyAnnotation(color="red",value="3",arrayAttr={6,7,8},annotationAttr=@MetaAnnotation(nextDay="1月15号")) //这个类应用了注解类MyAnnotation public class AnnotationTest { @SuppressWarnings("deprecation") //取消显示指定的编译器警告 @MyAnnotation("java")//只有一个属性值,value= 可以省略不写 public static void main(String[] args) throws Exception { //@SuppressWarnings("deprecation")加上注解后,编译器不会警告 System.runFinalizersOnExit(true);//这是一个过时的方法 if(AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)) { //利用反射得到AnnotationTest类的注解 MyAnnotation annotation=(MyAnnotation)AnnotationTest.class.getAnnotation(MyAnnotation.class); System.out.println(annotation.color()); System.out.println(annotation.value()); System.out.println(Arrays.toString(annotation.arrayAttr())); System.out.println(annotation.lamp()); System.out.println(annotation.annotationAttr().nextDay()); } //利用反射获取main方法的注解 MyAnnotation annotation1=(MyAnnotation)AnnotationTest.class.getMethod("main", String[].class).getAnnotation(MyAnnotation.class); System.out.println(annotation1.color());//默认是blue System.out.println(annotation1.value()); System.out.println(Arrays.toString(annotation1.arrayAttr())); System.out.println(annotation1.annotationAttr().nextDay()); } @Deprecated public static void say() { System.out.println("hello world!"); } }