Annotation功能可用于类、构造方法、成员变量、方法、参数等的声明中,该功能并不影响程序的运行,但是会对编译器警告等辅助工具产生影响。
在定义Annotation类型时,也需要用到用来定义接口的interface关键字,但需要在interface关键字前加一个“@”符号,即定义Annotation类型的关键字为@interface,这个关键字的隐含意思是继承了java.lang.annotation.Annotation接口。
下面通过一个例子来说明该功能的使用。
package com.lingzhuo.zhujie;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)//表示用于成员变量和枚举常量
@Retention(RetentionPolicy.RUNTIME)//表示在运行时加载Annotation到JVM中,有效范围最大。
public @interface MyAnnotation {
String nameAnnotation();
String sexAnnotation();
int ageAnnotation();
}
package com.lingzhuo.zhujie;
public class Student {
int age;//声明三个Student类的属性,并写出它们的三个set get方法
String name