------自定义注解元注解说明
- @Documented – 表示使用该注解的元素应被javadoc或类似工具文档化,它应用于类型声明,类型声明的注解会影响客户端对注解元素的使用。如果一个类型声明添加了Documented注解,那么它的注解会成为被注解元素的公共API的一部分。
2.@Target – 表示支持注解的程序元素的种类,一些可能的值有TYPE, METHOD, CONSTRUCTOR, FIELD等等。如果Target元注解不存在,那么该注解就可以使用在任何程序元素之上。Annotation可被用于 packages、types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。在Annotation类型的声明中使用了target可更加明晰其修饰的目标。
取值(ElementType)有:
(1)CONSTRUCTOR:用于描述构造器
(2)FIELD:用于描述域
(3)LOCAL_VARIABLE:用于描述局部变量
(4)METHOD:用于描述方法
(5)PACKAGE:用于描述包
(6)PARAMETER:用于描述参数
(7)TYPE:用于描述类、接口(包括注解类型) 或enum声明
3.@Retention - 该注解表示需要在什么级别保存该注释信息,用于描述注解的生命周期
取值(RetentionPoicy)有:
(1)SOURCE:在源文件中有效(即源文件保留)
(2)CLASS:在class文件中有效(即class保留)
(3)RUNTIME:在运行时有效(即运行时保留)
4.@Inherited - @Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。
实例:
(1)创建自定义注解
/**
* @author sam
* @since 2017/7/13
*/
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyMessage {
String name() default "sam";
int num() default 0;
String desc();
}
(2)创建测试类,使用自定义注解
package com.sam.annotation;
/**
* @author sam
* @since 2017/7/13
*/
public class AnnotationTest {
@MyMessage(num = 10, desc = "参数a")
private static int a;
@MyMessage(name = "Sam test", desc = "测试方法test")
public void test() {
System.out.println("test");
}
}
(3)使用反射机制处理自定义注解
package com.sam.annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 使用反射处理注解
*
* @author sam
* @since 2017/7/13
*/
public class MyMessageProcessor {
public static void main(String[] args) {
try {
//加载annotationTest.class类
Class clazz = MyMessageProcessor.class.getClassLoader().loadClass("com.sam.annotation.AnnotationTest");
//获取属性
Field[] fields = clazz.getDeclaredFields();
//遍历属性
for (Field field : fields) {
MyMessage myMessage = field.getAnnotation(MyMessage.class);
System.out.println("name:" + myMessage.name() + " num:" + myMessage.num() + " desc:" + myMessage.desc());
}
//获取类中的方法
Method[] methods = clazz.getMethods();
//遍历方法
for (Method method : methods) {
//判断方法是否带有MyMessage注解
if (method.isAnnotationPresent(MyMessage.class)) {
// 获取所有注解 method.getDeclaredAnnotations();
// 获取MyMessage注解
MyMessage myMessage = method.getAnnotation(MyMessage.class);
System.out.println("name:" + myMessage.name() + " num:" + myMessage.num() + " desc:" + myMessage.desc());
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}