package com.hu.Annotation;
由两个类来演示:AnnotationTest 和 MyAnnotation 其中前者用于结果的呈现。
/*
* Java中 java.lang包为我们提供了3个Annotation Types 注解类型:
* Depricated(过时),Override(对父类方法的覆盖),SuppressWarnings(忽略某一个注解)
*
*/
一.
importjava.lang.annotation.Annotation;
// 可以加多个Annotation
@MyAnnotation(annotationAttr =@MetaAnnotation ("biao"),color="red",value="abc",arrayAttr={1,2,3})
// 如果arrayAttr 就一个值就直接写成 arrayAttr=1省略大括号。
publicclass AnnotationTest
{
//@SuppressWarnings("deprecation")
@MyAnnotation("xyz")
public static void main(String [] args)throws Exception
{
if(AnnotationTest.class.isAnnotationPresent(MyAnnotation.class))
//反射获得 AnnotationTest类的注解。
{
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.arrayAttr().length);
//System.out.println(annotation.lamp().nextLamp().name());
System.out.println(annotation.annotationAttr().value());
//annotationAttr()这个方法返回的是一个注解。
}
}
}
二.
packagecom.hu.Annotation;
import java.lang.annotation.*;
// javac 在编译class文件的时候可能将注解去掉,因此要看到注解,需声明注解的生命周期
// 它有三个生命周期: RetentionPolicy.Source |RetentionPolicy.Class|RetentionPolicy.RUNTIME
//分别对应 : java源文件 | class文件 |内存中的字节码
@Retention(RetentionPolicy.RUNTIME) // 注解的注解叫元注解。意思是保留到运行期间。
@Target({ElementType.METHOD,ElementType.TYPE}) //表示注解放到哪个位置?此处表示作用在方法上,也可以在类上用,因为class父类是Type。
//那么也想作用到类上怎么办? (ElementType.METHOD,ElementType.Type) 即可。
public@interface MyAnnotation {
//为注解添加属性
// 不同的注解类型(class 、注解 、原始类型等等),怎么操作
String color () default"blue";
String value();
int[] arrayAttr() default {3,4,6};
//枚举类型的实例对象就是他的一个元素。
// Enum.TrafficLamp lamp() default Enum.TrafficLamp.RED ;
MetaAnnotation annotationAttr() default@MetaAnnotation ("hu");// @MetaAnnotation ("hu")这是MetaAnnotation的一个对象。
}