包 java.lang.annotation 中包含所有定义自定义注解所需用到的原注解和接口。 如接口 java.lang.annotation.Annotation 是所有注解继承的接口,并且是自动继承,不需要定义时指定,类似于所有类都自动继承Object。 该包同时定义了四个元注解,Documented,Inherited,Target(作用范围,方法,属性,构造方法等),Retention(生命范围,源代码,class,runtime)。
@Target 表示该注解用于什么地方,可能的值在枚举类 ElemenetType 中,包括: ElemenetType.CONSTRUCTOR—————————-构造器声明 ElemenetType.FIELD ————————————–域声明(包括 enum 实例) ElemenetType.LOCAL_VARIABLE————————- 局部变量声明 ElemenetType.METHOD ———————————-方法声明 ElemenetType.PACKAGE ——————————— 包声明 ElemenetType.PARAMETER ——————————参数声明 ElemenetType.TYPE————————————— 类,接口(包括注解类型)或enum声明
@Retention 表示在什么级别保存该注解信息。可选的参数值在枚举类型 RetentionPolicy 中,包括: RetentionPolicy.SOURCE ———————————注解将被编译器丢弃 RetentionPolicy.CLASS ———————————–注解在class文件中可用,但会被VM丢弃 RetentionPolicy.RUNTIME VM——-将在运行期也保留注释,因此可以通过反射机制读取注解的信息。
@Documented 将此注解包含在 javadoc 中 ,它代表着此注解会被javadoc工具提取成文档。在doc文档中的内容会因为此注解的信息内容不同而不同。相当与@see,@param 等。
@Inherited 允许子类继承父类中的注解
1.先定义一个能够用在类上的注解
@Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface MyAnnotation1 { String value(); }
2.再定义一个能够用在方法上的注解
@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface MyAnnotation2 { String description(); boolean isAnnotation(); }
3.测试类。给类加上MyAnnotation1注解,给方法加上MyAnnotation2注解
@MyAnnotation1("this is annotation1") public class AnnotationDemo { @MyAnnotation2(description = "this is annotation2", isAnnotation = true) public void sayHello() { System.out.println("hello world!"); } }
4.测试说明类
public class Annotation { public static void main(String[] args) throws Exception { Class<?> cls = Class.forName("annotation.AnnotationDemo"); // 判断AnnotationDemo是否有MyAnnotation1的注解 boolean flag = cls.isAnnotationPresent(MyAnnotation1.class); if (flag) { System.out.println("判断类是annotation"); MyAnnotation1 annotation1 = cls.getAnnotation(MyAnnotation1.class); System.out.println(annotation1.value()); } Method method = cls.getMethod("sayHello"); // 判断sayHello方法是否有MyAnnotation2的注解 flag = method.isAnnotationPresent(MyAnnotation2.class); if (flag) { System.out.println("判断方法也是annotation"); MyAnnotation2 annotation2 = method.getAnnotation(MyAnnotation2.class); System.out.println(annotation2.description() + "\t" + annotation2.isAnnotation()); } } }
5.控制台输出
判断类是annotation this is annotation1 判断方法也是annotation this is annotation2 true
Annotation与interface的异同: Annotation类型使用关键字@interface而不是interface。这个关键字声明隐含了一个信息:它是继承了java.lang.annotation.Annotation接口,并非声明了一个interface Annotation类型、方法定义是独特的、受限制的。Annotation 类型的方法必须声明为无参数、无异常抛出的。这些方法定义了annotation的成员:方法名成为了成员名,而方法返回值成为了成员的类型。方法的后面可以使用 default和一个默认数值来声明成员的默认值,null不能作为成员默认值,这与我们在非annotation类型中定义方法有很大不同。 Annotation类型又与接口有着近似之处。它们可以定义常量、静态成员类型(比如枚举类型定义)。Annotation类型也可以如接口一般被实现或者继承。
参考 http://blog.csdn.net/hbcui1984/article/details/4735487 http://www.cnblogs.com/cr330326/p/5695474.html
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句