黑马程序员-笔记-15-注解

来源:互联网 发布:医疗软件 编辑:程序博客网 时间:2024/06/06 09:49

-------------------- ASP.Net+Android+IOS开发.Net培训、期待与您交流! ----------------------

@MyAnnotation(111)//如果注解中只有value()这一个属性需要赋值,那么前边的value=可以省略。public class AnnotationTest {/** * 注解:注解是一种标记,加上注解以后,开放工具以及编译器就可以 * 通过反射来了解你的类以及各个元素上有没有标记,看你的标记,决定怎么执行。 * 标记可以加在:包,类,字段,方法,方法的参数,以及局部变量上。 */@MyAnnotation(value = 123,array=4,annotation=@metaAnnotation("changeAnnotation"))//注解中数组元素的赋值,如果数组只有一个值,那么可以省略{}@SuppressWarnings("deprecation")public static void main(String[] args) {System.runFinalizersOnExit(true);//判断一个注解是否存在于当前类上,这个注解必须是运行时注解,一个注解就相当于这个注解类的一个实例对象。if(AnnotationTest.class.isAnnotationPresent(MyAnnotation.class)){//如果次注解存在多个,那么这个取得注解的方法默认取第一个。MyAnnotation annotation = (MyAnnotation)AnnotationTest.class.getAnnotation(MyAnnotation.class);System.out.println(annotation);//获取注解的属性。System.out.println(annotation.color());System.out.println(annotation.value());System.out.println(annotation.array().length);System.out.println(annotation.enumTest1().name());//没能取出来这个非public的枚举。可能是annotation跟它不同包。//System.out.println(annotation.enumTest2().name());System.out.println(annotation.annotation());}}//声明一个方法过时。@Deprecatedpublic static void test(int i){System.out.println("test");}}

上边使用的到的MyAnnotation注解:

/** * 创建注解:@interface 注解本身也可以存在注解。 *  * 元注解: 注解的注解。 *  * 注解的生命周期: java源文件 class文件 内存中的字节码 通过@Retention这个注解声明该注解所存在的阶段。默认值实在class阶段。 *  * @Override,@SupperssWarnings: 编译器看到使用完毕后,这个注解就没有存在的价值了,所以他的生命周期在Java源文件。 * @deprecated:在运行时jvm依然需要二进制代码中他是否过时,所以他是生命周期一直在内存中,即运行时。。 *  *注解的作用范围: *可以使用元注解@Target来声明一个注解的使用位置。 *ElementType.TYPE:可以作用与接口,或者class上。 */@Target({ ElementType.METHOD, ElementType.TYPE })@Retention(RetentionPolicy.RUNTIME)public @interface MyAnnotation {// 给注解添加属性。String color() default "red";// 默认前缀public abstract,可以省略。int value();int[] array() default { 1, 2, 3 };EnumTest.WeekDay enumTest1() default EnumTest.WeekDay.SUN;Test enumTest2() default Test.TEST1;//这个非public类型的枚举,没有办法取出来。metaAnnotation annotation() default @metaAnnotation("metaAnnotation");}enum Test{TEST1,TEST2;public Test next(){if(this==TEST1)return TEST2;elsereturn TEST1;}}

MyAnnotation中使用到的元注解metaAnnotation:

package itcast.day2;public @interface metaAnnotation {String value();}