一、自定义注释
1、自定义Annotation的格式
[public] @interface Annotation名称{
数据类型 变量名称 ();
}
提示:使用@interface就相当于继承了Annotation接口。
示例一:在Annotation中设置多个属性
public @interface AnnotationWithParam {
public String key();
public String value();
}
示例二:在Annotation中设置数组属性
public @interface AnnotationWithArrayParam {
public String[] value(); // 接收设置的内容是一个字符串数组
}
2、Annotation定义变量的默认值
[public] @interface Annotation名称{
数据类型 变量名称 () default 默认值;
}
example:
public @interface AnnotationWithParam {
public String key() defalut "zhangsan";
public String value() defalut "张三";
}
3、使用枚举限制设置的内容
/***定义枚举类***************/
public enum Name {
ZSM,LX,LIU
}
/*****自定义Annotation类****/
public @interface AnnotationEnum {
public Name name() default Name.ZSM;
}
提示:这样定义的Annotation,在使用AnnotationEnum时,所有的取值就必须从Name这个枚举中取得。
二、相关内建注释知识介绍
1) @Retention:用于定义一个Annotation的保存范围。在Retention定义中存在一个RetentionPolicy的变量,此变量用于指定Annotation的保存范围。RetentionPolicy包含如下3个范围:
(1) SOURCE: 此Annotation类型的信息只会保留在程序源文件中(*.java),编译之后不会保存在编译好的类文件(*.class)中;
(2) CLASS: 默认范围。此Annotation类型的信息只会保留在程序源文件中(*.java)和编译之后 的 类文件(*.class)中。在使用此类时,这些Annotation信息将不会被夹在到虚拟机(JVM)中;
(3) runtime: 此Annotation类型的信息保留在源文件(*.java)、类文件(*.class)中,在执行时也会加载到JVM中。
2) @Target: 用于指定注释出现的位置(类、方法或属性)。在Target定义存在ElememtType[]枚举类型的变量,这个变量主要指定Annotation的使用限制。
public enum ElementType {
TYPE, // 只能用在类、接口、枚举类型上
FIELD,
METHOD,
PARAMETER, // 只能用在参数的声明上
CONSTRUCTOR, // 只能用在构造器的声明上
LOCAL_VARIABLE,// 只能用在局部变量的声明上
ANNOTATION_TYPE,// 只能用在注释的声明上
PACKAGE
}
3) @Inherit:用于标注一个父类的注释是否可以被之类所继承,如果一个Annotation需要被其之类所继承,则在声明时直接使用@Inherit注释即可。
三、通过反射取得Annotation
如果想让一个Annotation其作用,则必须结合反射机制。Class类中存在以下几种与Annotation操作有关的方法:
public <A extends Annotation> A getAnnotation(Class<A> annotationClass)
如果在一个元素中存在注释,则取得全部注释
public Annotation[] getAnnotations()
返回此元素上的所有注释
public Annotation[] getDeclaredAnnotations()
返回直接存放在此元素上的所有注释
public boolean isAnnotation()
判断元素是否表示一个注释
public boolean isAnnotionPresent(Class<? extends Annotation> annotationClass)
判断一个元素上是否存在注释
示例(annotation继承):
@Inherited
@Retention(value=RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
public String name();
}
@MyAnnotation(name="zsm")
public class Person {}
public class Student extends Person{}
@SuppressWarnings({"unchecked","rawtypes"})
public class AnnotationInheritTest {
public static void main(String[] args) throws ClassNotFoundException {
Class clazz = Class.forName("org.zsm.annnotation.Student");
Annotation[] annotations = clazz.getAnnotations(); // 获取所有的Annotations
for(Annotation annotation : annotations){
System.out.println(annotation);
}
if(clazz.isAnnotationPresent(MyAnnotation.class)){
MyAnnotation myAnnotation = (MyAnnotation) clazz.getAnnotation(MyAnnotation.class);
System.out.println(myAnnotation.name());
}
}
}
转载于:https://my.oschina.net/u/1425545/blog/210661